#!/bin/usr/python3
import os
import sys
from string import Template

import argparse
import shutil

from utils import config
from utils.snx import Snx, SnxExecutable, SnxHooks
from wxUI.task_bar_icon import App


def init_hooks():
    if os.geteuid() == 0:
        if not os.path.exists('/etc/snxtray'):
            os.makedirs('/etc/snxtray')
        shutil.copy(config.UP, config.POLKIT_ACTIONS)
        shutil.copy(config.DOWN, config.POLKIT_ACTIONS)
        shutil.copy(config.POST_UP, config.POLKIT_ACTIONS)
        shutil.copy(config.POST_DOWN, config.POLKIT_ACTIONSt)
        with open('/etc/snxtray/up', 'w') as up:
            up.write('#!/bin/bash\n')
            up.write(Template('snx -s $server -c $cert\n').substitute({'server': config.server, 'cert': config.cert}))
            up.write('/etc/snxtray/post-up')
        with open('/etc/snxtray/down', 'w') as up:
            up.write('#!/bin/bash\n')
            up.write('snx -d\n')
            up.write('/etc/snxtray/post-down')
        with open('/etc/snxtray/post-up', 'w') as up:
            up.write('#!/bin/bash')
        with open('/etc/snxtray/post-down', 'w') as up:
            up.write('#!/bin/bash')
        os.chmod('/etc/snxtray/up', 0o0555)
        os.chmod('/etc/snxtray/down', 0o0555)
        os.chmod('/etc/snxtray/post-up', 0o0555)
        os.chmod('/etc/snxtray/post-down', 0o0555)
        return True
    else:
        print('root required')
        return False


def main():
    parser = argparse.ArgumentParser(prog='snxtry', description='manage your snx from your systemtry')
    parser.add_argument('--init-hooks', action='store_true', dest='inithooks', default=False,
                        help='install hook with pkexec needs sudo')
    #parser.add_argument('-d', action='store_true', dest='daemon', default=False,
    #                    help='fork to background')
    results = vars(parser.parse_args())

    if results['inithooks'] == True:
        config.init()
        if init_hooks():
            sys.exit(0)
        else:
            sys.exit(1)

    #if results['daemon'] == True:
    #    if os.fork():
    #        sys.exit()

    config.init()

    if config.elevate == 'hooks':
        config.Client = SnxHooks()
    else:
        config.Client = SnxExecutable()

    app = App(False)

    app.MainLoop()


if __name__ == '__main__':
    main()
