#!/usr/bin/python3
"""Create /etc/vpn-router/vpn-router.conf from the installer's answers.

Runs once, from postinst, and only when the file does not exist. The
configuration file belongs to the operator from that point on and is never
rewritten by the package.

Answers arrive as VPN_ROUTER_* environment variables. The pre-shared key is
stored base64-encoded so that arbitrary characters cannot collide with INI
syntax.
"""

import base64
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))

import vpnrouter

# environment variable -> (section, option)
ANSWERS = {
    'VPN_ROUTER_PLATFORM':        ('general', 'platform'),
    'VPN_ROUTER_EXTERNAL_INTERFACE': ('interfaces', 'external'),
    'VPN_ROUTER_INTERNAL_INTERFACE': ('interfaces', 'internal'),
    'VPN_ROUTER_LOCAL_FQDN':      ('wan', 'local_fqdn'),
    'VPN_ROUTER_LOCAL_ID_MODE':   ('wan', 'local_id_mode'),
    'VPN_ROUTER_LOCAL_CIDRS':     ('local', 'cidrs'),
    'VPN_ROUTER_INT_GATEWAY_IP':  ('local', 'int_gateway_ip'),
    'VPN_ROUTER_REMOTE_ADDRS':    ('remote', 'addrs'),
    'VPN_ROUTER_REMOTE_ID':       ('remote', 'id'),
    'VPN_ROUTER_REMOTE_CIDRS':    ('remote', 'cidrs'),
    'VPN_ROUTER_P2S_ENABLED':     ('p2s', 'enabled'),
    'VPN_ROUTER_P2S_ADDRESS_POOL': ('p2s', 'address_pool'),
    'VPN_ROUTER_P2S_CA_NAME':     ('p2s', 'ca_name'),
    'VPN_ROUTER_WG_ENABLED':      ('wireguard', 'enabled'),
    'VPN_ROUTER_WG_ADDRESS':      ('wireguard', 'address'),
    'VPN_ROUTER_WG_LISTEN_PORT':  ('wireguard', 'listen_port'),
}


def main():
    path = vpnrouter.CONFIG_FILE
    if path.exists():
        return 0

    parser = vpnrouter.default_parser()

    for variable, (section, option) in ANSWERS.items():
        value = os.environ.get(variable)
        if value is not None and value != '':
            parser[section][option] = value

    psk = os.environ.get('VPN_ROUTER_PSK', '')
    if psk:
        parser['remote']['psk_b64'] = base64.b64encode(
            psk.encode('utf-8')).decode('ascii')

    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, 'w', encoding='utf-8') as handle:
        parser.write(handle)
    os.chmod(path, 0o600)
    os.chown(path, 0, 0)

    print(f'vpn-router: wrote {path}')
    print('vpn-router: edit it and run "systemctl restart vpn-router-setup" '
          'to apply changes')
    return 0


if __name__ == '__main__':
    sys.exit(main())
