#!/usr/bin/python3
import sys, os, requests, configparser, time, subprocess
SLEEPTIME = 600

if os.path.exists('./registrar.ini'):
    config = './registrar.ini'
elif os.path.exists('/etc/registrar.ini'):
    config = '/etc/registrar.ini'

if config:
    cfg = configparser.ConfigParser()
    cfg.read(config)

if 'REGISTRAR' in cfg:
    if 'URL' in cfg['REGISTRAR']:
        URL = cfg['REGISTRAR']['URL']

if 'AUTORUN' in cfg:
    if 'SLEEPTIME' in cfg['AUTORUN']:
        SLEEPTIME = int(cfg['AUTORUN']['SLEEPTIME'])

try:
    with open('/etc/machine-id', 'r') as fmachine:
        for line in fmachine.readlines():
            if len(line.strip()) == 32:
                machine_id = line.strip()
                break 
except:
    print('cannot get machine_id')
    quit()

home_dir = os.environ.get('HOME')
desktop_dir = os.path.join(home_dir, 'Desktop')
if home_dir:
    if os.path.exists(os.path.join(home_dir, '.config/user-dirs.dirs')):
        with open(os.path.join(home_dir, '.config/user-dirs.dirs')) as f:
            for a in f.readlines():
                if 'XDG_DESKTOP_DIR' in a:
                    desktop_dir = a.split('=')[1].replace('$HOME', home_dir)
                    break
subprocess.call(f'cp -f /usr/share/applications/support_pay.desktop {desktop_dir}' , shell=True)
os.chmod(os.path.join(desktop_dir.strip('"\n'), 'support_pay.desktop'), 0o755 )


def check():
    while True:
        print('Check registration...')
        try:
            response =  requests.get(URL + 'status.py', 
                    params=[ ( 'machine_id', machine_id ),
                             ( 'counter', 1 ) ] )
            registrated = False
            if response.status_code == 200:
                for a in response.text.split('\n'):
                    if a.startswith('<') or not a.strip():
                        continue
                    if a.startswith('counter:'):
                        print(a)
                        registrated = True
                        break
                if registrated:
                    return True
                return False
        except:
            time.sleep(SLEEPTIME)

while not check():
    subprocess.call('/usr/bin/registrar')
    time.sleep(SLEEPTIME)
