#!/usr/bin/env python3



import birchenv
import os
import shutil
import subprocess
import sys
import threading
import time

__author__="alvare"
__date__ ="11-Jan-2020"

if __name__ == "__main__":
    print("Not an executable module!")
    exit()


def Cleanrun(cmds, rm_list=[], fork=True):
    '''
    cmds - a command, with arguments passed as a list, as described in subprocess.call.
    rm_list - list of files to remove after command has terminated
    fork - if fork = True, run in the background as a separate process
    '''
    if fork:
        pid = os.fork()
        if not pid:
            run_clean(cmds, rm_list)
            sys.exit()
    else:
        #thread.start_new_thread(run_clean, [cmds, rm_list]) # python2
        T = threading.Thread(run_clean, [cmds, rm_list])
        T.start()

def run_clean(cmds, rm_list=[]):
    '''
    In the current implementation, run_clean waits 5 seconds after running
    the commands before deleting files in rm_list. This should really be replaced
    with a more deterministic way of doing things. Ideally, the remove command should
    actually be part of the command list.
    '''
    for cmd_run in cmds :
        subprocess.call(cmd_run)
    time.sleep(5)
    for rm_file in rm_list:
        os.remove(rm_file)

def forkrun(popenargs, ENV=None):
    pid = os.fork()
    if not pid:
        if ENV:
            subprocess.call(popenargs, env=ENV)
        else:
            subprocess.call(popenargs)


def cat_to(INFILE, h_OUTFILE):
    '''
    Write the contents of one file to a new file
    '''
    h_temp = open(INFILE)
    for line in h_temp:
        h_OUTFILE.write(line)
    h_temp.close()


def choosehost():
    '''
    Choose a remote host on which to execute a program.
    Currently, this is dumb function whose sole task
    is to rotate a list of hosts in $BIRCH/.BIRCHrhosts
    so that no one host always gets jobs. It should be
    replaced with a more sophisticated function that finds hosts
    that the user has permissions to execute programs on.
    '''
    # Make sure the remote host file exists
    if not os.path.exists(os.path.join(birchenv.HOME, '.BIRCHrhosts')):
        shutil.copyfile(os.path.join(birchenv.BIRCH, 'local', 'admin', 'BIRCHrhosts'),
            os.path.join(birchenv.HOME, '.BIRCHrhosts'))

    #Rotate the list, putting the current host to the bottom.
    h_hosts_file = open(os.path.join(birchenv.HOME, '.BIRCHrhosts'), 'r')
    host_list = h_hosts_file.readlines()
    h_hosts_file.close()

    h_hosts_file = open(os.path.join(birchenv.HOME, '.BIRCHrhosts'), 'w')
    for host in host_list[1:]:
        h_hosts_file.write(host)
    h_hosts_file.write(host_list[0])
    h_hosts_file.close()

    # Write out the current host name
    return host_list[0].rstrip("\r\n")
