#!/usr/bin/python3
# -*- coding: utf-8 -*-

from pathlib import Path
import os
import click


PATH = Path('/etc/wireguard')
interface_path = PATH / f'wg0.conf'

def check_exist():
    if os.popen(f'(sudo ls {interface_path} && echo true) || echo false').read() == 'true':
        click.echo(f"Wireguard Interface Does Not Exist")
        return False
    click.echo(f"Wireguard Interface Exists")
    return True

@click.group()
def cli():
    pass

@cli.command()
@click.argument('config_path', type=click.Path(exists=True))
def add(config_path):
    if check_exist():
        if click.confirm('Overwrite previous Wireguard config?'):
            click.echo(f'Previous config will be stored at {interface_path}.old')
            os.system(f'sudo mv {interface_path} {interface_path}.old')
        else:
            return
    os.popen(f'sudo cp {config_path} {interface_path}')
    os.popen(f'sudo wg-quick up wg0')

@cli.command()
@click.option('-y', is_flag=True, help="Skip confirmation")
def remove(y):
    if not check_exist(): return

    if y or click.confirm(f'Remove interface wg0?'):
        os.system(f'sudo wg-quick down {interface_path}')
        os.system(f'sudo rm {interface_path}')

@cli.command()
def start():
    if not check_exist(): return

    os.system('sudo systemctl start wg-quick@wg0')
    os.system('sudo wg-quick up wg0')
    click.echo('Wireguard Interface Started')

@cli.command()
def stop():
    if not check_exist(): return

    os.system('sudo systemctl stop wg-quick@wg0')
    os.system('sudo wg-quick down wg0')
    click.echo('Wireguard Interface Stopped')

@cli.command()
def enable():
    if not check_exist(): return

    os.system('sudo wg-quick up wg0')
    os.system('sudo systemctl enable wg-quick@wg0')
    os.system('sudo systemctl daemon-reload')
    click.echo('Wireguard Interface Enabled')


@cli.command()
def disable():
    if not check_exist(): return

    os.system('sudo systemctl stop wg-quick@wg0')
    os.system('sudo systemctl disable wg-quick@wg0.service')
    os.system('sudo systemctl daemon-reload')
    click.echo('Wireguard Interface Disabled')

cli.add_command(add)
cli.add_command(remove)
cli.add_command(start)
cli.add_command(stop)
cli.add_command(enable)
cli.add_command(disable)

if __name__ == '__main__':
    cli()
