#!/usr/bin/env python
#
# Bootstrap for kforge automatic testing.
# Will pass through any command line arguments supplied to the script

import os
import commands
import urllib
import sys
import tempfile

verbose = True
def _print(msg, isError=False):
    if verbose:
        print(msg)

scriptName = 'kforge-integrationtest'
url = 'http://project.knowledgeforge.net/kforge/svn/trunk/bin/%s' % scriptName

def main(argv):
    # reconstruct the command line args
    args = ''
    if len(argv) > 1:
        args = ' '.join(argv[1:])
    # temp file to store the script in
    (fd, filename) = tempfile.mkstemp(prefix=scriptName)
    _print('Downloading and executing %s...' % (scriptName))

    try:
        urllib.urlretrieve(url, filename)
        _print('Downloaded %s to %s.' % (url, filename))
        cmd = 'python '  + filename + ' ' + args
        _print('Attempting to execute %s' % cmd)
        # order of messages to stdout and stderr do not come out correctly
        # status, output = commands.getstatusoutput(cmd)
        # if status: _print(output, True)
        # else: _print(output)
        # WARN: using os.system means that all messages will get printed 
        status = os.system(cmd)
        _print('Downloading and execution completed.')
        return status
    finally:
        os.remove(filename)

if __name__ == '__main__':
    status = main(sys.argv)
    if status:
        sys.exit(1)
