#!/usr/bin/env python3
import argparse
import importlib
import os
import subprocess
import sys

import impl_amrfinder

# N.B. This code represents the minimum functionallity required to
#      download and update the latest version of the code. As such
#      resist updating this code as much as possible. All changes
#      should be made in impl_armfinder.py

def main():
    parse = argparse.ArgumentParser(add_help=False)
    parse.add_argument('-x', '--check-update', help='Check for any updates to this pipeline (default: %(default)s)', action='store_true')
    parse.add_argument('-u', '--update', help='Update this code from the source control system (default: %(default)s)', action='store_true')
    parse.add_argument('-v', '--version', action='store_true', help='Print version information')

    args, remaining_argv = parse.parse_known_args()

    if args.version:
        impl_amrfinder.print_versions()
        sys.exit(0)
    
    if args.update:
        script_path = os.path.dirname(os.path.realpath(__file__))
        print("Checking for update...", file=sys.stderr, end='')
        svn = subprocess.run(["svn", "update", script_path],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        if svn.returncode == 0:
            print("success!", file=sys.stderr)
            importlib.reload(impl_amrfinder)
        else:
            print("failure.", file=sys.stderr)

    impl_amrfinder.run(parse)

    sys.exit(0) #success

if __name__ == "__main__":
    main()
