#!/usr/bin/env python3
import argparse
import shlex
from pathlib import Path
from subprocess import check_call, run

from grasp_server import setup_parser

SYSTEMD_CONFIG = """
[Unit]
Description=Grasp extension server conterpart

[Install]
WantedBy=default.target

[Service]
ExecStart={server} {extra_args}
Type=simple
Restart=always
"""


def systemd(*args, method=check_call):
    method([
        'systemctl', '--user', *args,
    ])

def setup(args):
    base_path = '~/.config/systemd/user'
    if not Path(base_path).expanduser().is_dir():
        Path(base_path).expanduser().mkdir(parents=True, exist_ok=True)

    unit_name = args.unit_name
    out = Path(f'{base_path}/{unit_name}').expanduser()
    print(f"Writing systemd config to {out}:")

    server_bin = Path(__file__).parent.joinpath('grasp_server.py').absolute()

    template = args.template.replace('%', '%%').replace('\n', r'\n') # escape for systemd...
    template = shlex.quote(template)
    extra_args = f'--port {args.port} --path {args.path} --template {template}'

    with out.open('w') as fo:
        fo.write(SYSTEMD_CONFIG.format(
            server=server_bin,
            extra_args=extra_args,
        ))
    try:
        systemd('stop' , unit_name, method=run) # ignore errors here if it wasn't running in the first place
        systemd('daemon-reload')
        systemd('enable', unit_name)
        systemd('start' , unit_name)
        systemd('status', unit_name)
    except Exception as e:
        print(f"Something has gone wrong... you might want to use 'journalctl --user -u {unit_name}' to debug")
        raise e

def main():
    p = argparse.ArgumentParser('grasp server setup', formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, width=100)) # type: ignore
    p.add_argument('--unit-name', type=str, default='grasp.service', help='Systemd unit name')
    setup_parser(p)
    args = p.parse_args()
    setup(args)

if __name__ == '__main__':
    main()