#!/usr/bin/python3
"""Install the packages of a feature from the Ubuntu archive, then restart vpn-router-setup without waiting.

Run by vpn-router-install@<feature>.service, which vpn-router-setup starts when the feature is on and its packages are
missing: webdav (rclone) and dns (PowerDNS with its gpgsql backend). Recommended packages are left out, so PowerDNS
comes without its bind backend. A failure is a message on standard error and the exit status 1.

  install-packages FEATURE
"""

import os
import subprocess
import sys

#: The packages of each feature.
FEATURES = {'webdav': ['rclone'], 'dns': ['pdns-server', 'pdns-backend-pgsql']}

#: apt-get, waiting up to ten minutes for dpkg's lock, which a package installation that runs setup holds.
APT = ['apt-get', '-o', 'DPkg::Lock::Timeout=600']


def main():
    if len(sys.argv) != 2 or sys.argv[1] not in FEATURES:
        sys.exit(f'usage: install-packages {"|".join(FEATURES)}')
    environment = dict(os.environ, DEBIAN_FRONTEND='noninteractive')
    for args in ([*APT, 'update'], [*APT, '-y', '--no-install-recommends', '-o', 'Dpkg::Options::=--force-confdef',
                                    '-o', 'Dpkg::Options::=--force-confold', 'install', *FEATURES[sys.argv[1]]]):
        print(f'$ {" ".join(args)}', flush=True)
        if subprocess.run(args, env=environment).returncode != 0:
            sys.exit(f'install-packages: {args[0]} failed')
    subprocess.run(['systemctl', 'restart', '--no-block', 'vpn-router-setup.service'])
    return 0


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