import requests
import json
import string
import random
import glob, os
import sys

path = "../../../gradle.properties"
gw_url=os.popen('. ../../../gradle.properties\necho "${gateway_url}"').read().replace('\n', '')
if len(sys.argv) > 1:
    gw_url=sys.argv[1]

print(gw_url)
gateway = requests.get(gw_url).json()
print(gateway)

with open(path, "r") as f:
    lines = f.readlines()

with open(path, "w") as f_w:
    for line in lines:
        if "base_url=" in line:
            line = "base_url=\"%s\"\n"%(gateway['rest'][0])

        elif "harvest_ip=" in line:
            harvester=gateway['harvester'][0].split(":")
            line = "harvest_ip=\"%s:%s\"\n"%(harvester[0],harvester[1])

        elif "harvest_port=" in line:
            line = "harvest_port=%s\n"%(gateway['harvester'][0].split(":")[2])

        elif "gateway_ip=" in line:
            ip = gateway['gateway'][0]
            if len(gateway['gateway']) > 1:
                ip = gateway['gateway'][1]
            line = "gateway_ip=\"%s\"\n"%(ip)

        elif "repayment_h5=" in line:
            line = "repayment_h5=\"%s\"\n"%(gateway['repay'][0])

        elif "admin_host=" in line:
            line = "admin_host=\"%s\"\n"%(gateway['admin'][0])

        elif "agreement_url=" in line:
            line = "agreement_url=\"%s\"\n"%(gateway['privacy'][0])

        elif "home=" in line and "home" in gateway.keys():
            line = "home=\"%s\"\n"%(gateway['home'][0])

        line = line.replace("http:","https:")
        f_w.write(line)


