import os
import uuid
import subprocess
import requests
import threading
import json

# Check for shepherd.new file in edit conf dir. If there,
# or if no shepherd.id file can be found, generate a new one. 
# For now, also attempt to delete /var/lib/zerotier-one/identity.public and identity.secret
# Once generated, if it was due to shepherd.new file, delete it.


#Start new thread, and push ID and core config to api.shepherd.distreon.net/client/update

client_id = None

def _update_job(core_config):
    payload = {"client_id":client_id, "core_config":core_config}
    json_string = json.dumps(payload)
    try:
        r = requests.post('http://api.shepherd.distreon.net/client/update', data=json_string)
    except requests.exceptions.ConnectionError:
        pass

def generate_new_zerotier_id():
    print("Removing old Zerotier id files")
    try:
        os.remove("/var/lib/zerotier-one/identity.public")
        os.remove("/var/lib/zerotier-one/identity.secret")
    except:
        pass
    print("Restarting Zerotier systemd service to regenerate ID")
    subprocess.run(["systemctl", "restart", "zerotier-one.service"])

def generate_new_id(root_dir):
    global client_id
    with open(os.path.join(root_dir, "shepherd.id"), 'w+') as f:
        new_id = uuid.uuid1()
        client_id = str(new_id)
        f.write(client_id)
    generate_new_zerotier_id()

def init_control(core_config):
    global client_id
    root_dir = os.path.expanduser(core_config["root_dir"])
    editconf_dir = os.path.dirname(os.path.expanduser(core_config["conf_edit_path"]))

    if os.path.isfile(os.path.join(editconf_dir, "shepherd.new")):
        generate_new_id(root_dir)
        os.remove(os.path.join(editconf_dir, "shepherd.new"))
    elif not os.path.isfile(os.path.join(root_dir, "shepherd.id")):
        generate_new_id(root_dir)
    else:
        with open(os.path.join(root_dir, "shepherd.id"), 'r') as id_file:
            client_id = id_file.readline().strip()

    print(F"Client ID is: {client_id}")

    control_thread = threading.Thread(target=_update_job, args=(core_config,))
    control_thread.start()
        
