#!/usr/bin/python
#
# Copyright (c) 2011-2022 Andreas Gustafsson.  All rights reserved.
# Please refer to the file COPYRIGHT for detailed copyright information.
#

from __future__ import print_function

from bracket import *

import tempfile
import optparse

root = config['precommit_root']

# Generate a running job number

def gen_jobno():
    fn = os.path.join(root, 'jobno')
    fnl = lock(fn)
    s = read_file(fn, 't')
    if s == '':
        s = '0'
    n = int(s)
    n = n + 1
    write_file(fn, str(n), 't')
    del fnl
    return n

def test_patch_server_main(argv):
    parser = optparse.OptionParser()
    parser.add_option("--base", help="apply patches to sources from DATE",
                      metavar="DATE")

    (options, args) = parser.parse_args(argv)

    jobid = "run-%06i" % gen_jobno()

    # Create a working directory for this job
    d = os.path.join(root, jobid)
    mkdir_p(d)

    print("using directory", d)

    # The directory in the source tree that the patch is relative to
    patch_dir = args[0]

    # Read the patch as binary data, as it can contain non-ASCII charcters
    if sys.version_info[0] >= 3:
        patch_data = sys.stdin.buffer.read()
    else:
        patch_data = sys.stdin.read()

    print("patch to apply in", patch_dir, ":")
    print(patch_data)

    patch_tempfile_fn = os.path.join(d, 'patch')
    write_file(patch_tempfile_fn, patch_data, 'b')

    if options.base:
        use_repository_for(rcs2ts(options.base))
    else:
        use_current_repository()

    # This is ugly: we are using the old results_root here, and
    # later switching to a different results_root

    def newest_successful_build():
        for ts in reversed(existing_build_dates()):
            if status2bool(get_cached_status_if_any(ts, 'build_status')):
                return ts
        raise RuntimeError("no successful build")

    if options.base:
        ts = rcs2ts(options.base)
        print("testing patch against base version:", ts2rcs(ts))
    else:
        ts = newest_successful_build()
        print("testing patch against the newest version known to have built successfully:", ts2rcs(ts))

    #config['build_root'] = os.path.join(d, 'work') # use shared ramdisk

    config['results_root'] = os.path.join(d, 'results')
    config['release_root'] = os.path.join(d, 'release')
    config['test_root'] = os.path.join(d, 'test')
    config['logdir'] = os.path.join(d, 'log')
    config['htmldir'] = '' # os.path.join(d, 'html')
    config['patch_dir'] = patch_dir
    config['patch_file'] = patch_tempfile_fn
    config['jobid'] = jobid

    #mkdir_p(config['build_root'])
    mkdir_p(config['results_root'])
    mkdir_p(config['test_root'])
    mkdir_p(config['logdir'])
    if config['htmldir'] != '':
        mkdir_p(config['htmldir'])

    test(test_op, ts)
