#!/usr/bin/python

import os
import sys
import re
import json
import subprocess

def get_slave_address():
    pipe = subprocess.Popen('grep "LOCAL_HOST_IP" /home/build/tools-tester.d/servers-local.conf | cut -d":" -f 2', shell=True, stdout=subprocess.PIPE)
    out = pipe.stdout.readlines()
    ip = str(out[0])
    ip = ip.replace("\n","")
    print ip
    return ip

for arg in sys.argv:
    print arg

#del line start with "repo" string from org file
with open(sys.argv[1],"r") as file_r:
    lines = file_r.readlines()
with open(sys.argv[1],"w") as file_w:
    for line in lines:
        if not re.search("^repo.*", line) and not re.search("^tpk_repo.*", line):
            file_w.write(line)

with open(sys.argv[2],"r") as file_json:
	json_dict = json.load(file_json)

with open(sys.argv[1],"a") as file_w:
        for line in json_dict[sys.argv[3]]:
            repo = str(line)
            if "localhost" in repo:
                ip = get_slave_address()
                #print ip,repo
                repo = repo.replace("localhost",ip)
                print repo
            file_w.write(repo + '\n')

if sys.argv[3] == "common-with-local-tpk-profile":
    ip = get_slave_address()
    tpkurl="http://"+ip+':'+"8881"+"/repo/TPK/org.tizen.calendar-1.0.0-x86.tpk"
    print tpkurl
    pipe = subprocess.call('sudo mkdir -p /home/build/tmp/mic/tpk',shell=True)
    cmdln = ["sudo","wget","-P","/home/build/tmp/mic/tpk",tpkurl]
    pipe2 = subprocess.Popen(cmdln)
