# -*- coding: utf-8 -*-
from setuphelpers import *
import time
import glob
import json
import base64
import time
# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls

apiurl = ''

def install():

    bin_name = glob.glob("*.zip")[0]
    namezip = bin_name.replace('.zip','')
    arch = namezip.split('-')[-1].split('.zip')[0]
    unzip(bin_name)

    copytree2(makepath(namezip,arch),'/opt/rustdesk')

    run('chmod +x /opt/rustdesk/hbbs')
    run('chmod +x /opt/rustdesk/hbbr')

    if type_redhat():
        if 'SELinux status:                 enabled' in run('sestatus'):
            run('restorecon -irv /opt/rustdesk/*')

    mkdirs('/var/log/rustdesk')

    with open('/etc/systemd/system/rustdesksignal.service','w') as f:
        f.write("""[Unit]
Description=Rustdesk Signal Server
[Service]
Type=simple
LimitNOFILE=1000000
ExecStart=/opt/rustdesk/hbbs
WorkingDirectory=/opt/rustdesk/
User=root
Group=root
Restart=always
StandardOutput=append:/var/log/rustdesk/signalserver.log
StandardError=append:/var/log/rustdesk/signalserver.error
# Restart service after 10 seconds if node service crashes
RestartSec=10
[Install]
WantedBy=multi-user.target""")

    run('systemctl daemon-reload')
    run('systemctl enable rustdesksignal.service')
    run('systemctl start rustdesksignal.service')

    with open('/etc/systemd/system/rustdeskrelay.service','w') as f:
        f.write("""[Unit]
Description=Rustdesk Relay Server
[Service]
Type=simple
LimitNOFILE=1000000
ExecStart=/opt/rustdesk/hbbr
WorkingDirectory=/opt/rustdesk/
User=root
Group=root
Restart=always
StandardOutput=append:/var/log/rustdesk/relayserver.log
StandardError=append:/var/log/rustdesk/relayserver.error
# Restart service after 10 seconds if node service crashes
RestartSec=10
[Install]
WantedBy=multi-user.target""")

    run('systemctl daemon-reload')
    run('systemctl enable rustdeskrelay.service')
    run('systemctl start rustdeskrelay.service')


def audit():

    hostname = open('/etc/hostname','r').read().strip('\n')
    nb=0
    while not glob.glob('/opt/rustdesk/*.pub'):
        nb=nb+1
        if nb == 120:
            error("'/opt/rustdesk/*.pub not found")
        time.sleep(1)

    pubkey = glob.glob('/opt/rustdesk/*.pub')[0]

    key = open(pubkey,'r').read()



    if not '.' in hostname:
        if not params.get("install_with_luti", False):
            error('please configure fqdn in /etc/hostname')

    print('fqdn use is %s' % hostname)

    config = {"host":hostname,"relay":hostname,"key":key,"api":apiurl}
    rustdesk_list = list(base64.b64encode(json.dumps(config,separators=(',', ':')).encode('utf-8')).decode('utf-8').replace('=',''))
    rustdesk_list.reverse()
    rustdesk_cfg = ''.join(rustdesk_list)

    data = {"config" : config, "rustdesk_cfg" : rustdesk_cfg}


    WAPT.write_audit_data_if_changed("rustdesk-server", 'rustdesk-server', data, max_count=365)
    return "OK"



