#-*- coding:UTF-8 -*-
import sys
import os
import getpass
import subprocess
import threading
import time
import datetime

RELAY_CLIENT_LOG = 'C:\\Users\\' + getpass.getuser() + '\\.meplus\\relayclient.log'
RELAY_WINDOWS_TEST_LOG = 'C:\\Users\\' + getpass.getuser() + '\\Desktop\\RelayTest\\testlog.txt'
_user_cmd = None

class UserCmd:
    def __init__(self):
        self.action = -1
        self.cmd = None

class UserCmdThread(threading.Thread):
    def __init__(self ,u_cmd):
        threading.Thread.__init__(self)
        self.cmd = u_cmd
        
    def run(self):
        print 'execUserCmd : ',self.cmd
        log_file = "D:\\p2p_log_" + str(datetime.date.today()) + ".txt"
        file_out = open(log_file ,'w')
        cmd_out = subprocess.Popen(args = self.cmd ,shell = True ,cwd = 'D:\\')
        while True:
            is_end = cmd_out.poll()
            if is_end == 0:
                break;
            line = cmd_out.stdout
            if line == None:
                time.sleep(1)
                continue
            else:
                print line
            
def doAction():
    if _user_cmd == None:
        print 'user cmd do not init.'
    if _user_cmd.action == 1001:
        try:
            os.remove(RELAY_CLIENT_LOG)
            os.remove(RELAY_WINDOWS_TEST_LOG)
        except WindowsError ,msg:
            print msg
    elif _user_cmd.action == 1002:
        if os.path.exists(RELAY_CLIENT_LOG):
            os.startfile(RELAY_CLIENT_LOG)
        else:
            print '\"' + RELAY_CLIENT_LOG + '\" not exist.'
        
        if os.path.exists(RELAY_WINDOWS_TEST_LOG):
            os.startfile(RELAY_WINDOWS_TEST_LOG)
        else:
            print '\"' + RELAY_WINDOWS_TEST_LOG + '\" not exist.'
  

if __name__ == '__main__':
    _user_cmd = UserCmd()
      
    for arg_item in range(1,len(sys.argv)):
        if sys.argv[arg_item].upper() == '-D':
            _user_cmd.action = 1001 # delete file
        elif sys.argv[arg_item].upper()  == '-S':
            _user_cmd.action = 1002 # open file
        elif sys.argv[arg_item].upper() == '-C':
            if (arg_item + 1) < len(sys.argv):
                _user_cmd.cmd = sys.argv[arg_item + 1]
            else:
                print 'user do not input cmd.'
       
    doAction()
    if _user_cmd.cmd <> None:
        _u_thread = UserCmdThread(_user_cmd.cmd)
        _u_thread.start()
        _u_thread.join()

    print '\n\nMain thread will exit ......'
