import os
import sys
import argparse
from shell_runner import ShellRunner
import time
import string
import platform
import re

parser=argparse.ArgumentParser()

parser.add_argument('-p','--casapkg', help='Tarball or .dmg', required=True)
parser.add_argument('-t','--target', help='Target branch e.g. master', required=True)
parser.add_argument('-w','--workdir', help='Working directory', required=True)
parser.add_argument('-s','--sourcebranch', help='Source branch e.g. pipe-123', required=True)
args = parser.parse_args()


pipeline_repo="https://open-bitbucket.nrao.edu/scm/pipe/pipeline.git"

casa_pkg = args.casapkg
work_dir = args.workdir
script_dir = os.path.dirname(os.path.abspath(__file__))

print("Casa package: " + casa_pkg)

shell = ShellRunner()

print("Platform: " + platform.system())
if (platform.system()=="Linux"):
    cmd = ('cp ' + casa_pkg + " " + work_dir)
    print (str(cmd))
    shell.runshell(cmd.split(), work_dir)

    cmd = ('tar xvf ' + casa_pkg )
    rc = shell.runshell(cmd.split(), work_dir)
    if rc != 0:
       raise Exception("Couldn't extract tarball")
  
    cmd = ('git clone ' + pipeline_repo)
    shell.runshell(cmd.split(), work_dir)
  
    cmd = ('git config --global user.name "bamboo"')
    rc = shell.runshell(cmd.split(), work_dir + "/pipeline")
    if rc != 0:
       raise Exception("Failed to set name.")

    cmd = ('git config --global user.email "bamboo_merge@.nrao.edu"')
    rc = shell.runshell(cmd.split(), work_dir + "/pipeline")
    if rc != 0:
       raise Exception("Failed to set email")

    cmd = ('git checkout ' + args.target)
    rc = shell.runshell(cmd.split(), work_dir + "/pipeline")
    if rc != 0:
       raise Exception("Checkout failed")
   
    cmd = ('git merge origin/' + args.sourcebranch)
    rc  = shell.runshell(cmd.split(), work_dir + "/pipeline")
    if rc != 0:
       raise Exception("Merge failed")
    

    env = os.environ.copy()
    casa_dir = re.sub(r'-py3\..?', '', os.path.basename(casa_pkg).replace(".tar.xz",""))
    casa_full_dir = work_dir + "/" + casa_dir 
    print("casadir: " + casa_dir)
    print("fullpath: " + casa_full_dir)

    env["PATH"] = casa_full_dir + ":" + casa_full_dir + "/bin:" + work_dir + "/pipeline" + ":" + env["PATH"]
    print(env)
    cmd = ( casa_full_dir + "/bin/pip3 install astropy==4.1 bdsf pympler==1.0.1")
    shell.runshell(cmd.split(), work_dir + "/pipeline", env)
    
    cmd = ( casa_full_dir + "/bin/python3 " +  work_dir + "/pipeline/setup.py install")
    shell.runshell(cmd.split(), work_dir + "/pipeline", env)

    shell.runshell([casa_full_dir + "/bin/python3", "-m","pytest", work_dir + "/pipeline", '--junitxml=' + work_dir + '/pipeline_test_result.xml'], work_dir + "/pipeline", env)

else:
    sys.exit("Unsupported platform: " + platform.system() )