#!/usr/bin/python3
"""Install the packages of a component from the Ubuntu archive, then have linux-manager-setup run without waiting.

Run by linux-manager-install@<component>.service, which linux-manager-setup starts when the component is on and its
packages are missing or marked as installed automatically: the components and their packages are
linuxmanager.COMPONENTS, the VPN, the router, the name server (PowerDNS with its gpgsql backend) and WebDAV (rclone).
Recommended packages are left out, so PowerDNS comes without its bind backend. apt-get marks the packages as installed
by hand. Installations of several components run one after another (INSTALL_LOCK), as apt locks its package lists.
A run of setup in progress, the one that started the installation, runs again when it ends (request_setup). A failure
is a message on standard error and the exit status 1.

  install-packages COMPONENT
"""

import fcntl
import os
import subprocess
import sys

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

import linuxmanager  # noqa: E402

#: The packages of each component.
FEATURES = {name: packages for name, (_, packages) in linuxmanager.COMPONENTS.items()}

#: The lock that has the installations of several components run one after another.
INSTALL_LOCK = '/run/linux-manager-install.lock'

#: 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')
    lock = open(INSTALL_LOCK, 'w', encoding='utf-8')
    fcntl.flock(lock, fcntl.LOCK_EX)
    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')
    lock.close()
    linuxmanager.request_setup()
    return 0


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