#!/usr/bin/env python3
from argparse import ArgumentParser
import subprocess
import sys
from os import path, remove

def fatal(msg):
    print(msg, file=sys.stderr)
    sys.exit(1)

if __name__ == '__main__':
    parser = ArgumentParser(
        description='Remove a client from VPN by name')
    parser.add_argument('name', help='Unique name for client')
    args = parser.parse_args()

    subprocess.run([
        'python3', '/usr/local/bin/wireguard-client-list.py',
        'sync'
    ], capture_output=True)
    ret = subprocess.run([
        'python3', '/usr/local/bin/wireguard-client-list.py',
        'show', args.name
    ], text=True, capture_output=True)

    if ret.returncode != 0:
        fatal(f'Could not find client with name: {args.name}')
    pubkey = ret.stdout.strip()

    ret = subprocess.run([
        'wg', 'set', 'wg0', 'peer', pubkey, 'remove', 
    ], capture_output=True)
    
    subprocess.run(['wg-quick', 'save', 'wg0'], capture_output=True)

    conf_path = f'/etc/wireguard/clients/{args.name}.conf'
    if path.isfile(conf_path):
        remove(conf_path)
    
    subprocess.run([
        'python3', '/usr/local/bin/wireguard-client-list.py',
        'sync'
    ])
