#!/usr/bin/python3
"""Fixed SIG repository updates. Root/systemd only; never accepts commands or paths."""
import configparser
import fcntl
import json
import os
from pathlib import Path
import pwd
import re
import signal
import stat
import subprocess
import sys
import tarfile
import tempfile
import time

REQUEST = Path('/var/lib/sig/update-request.json')
SPOOL = Path('/var/lib/sig-updates')
STATUS = SPOOL / 'status.json'
ETC = Path('/etc/sig')
STATE = Path('/var/lib/sig')
NETWORK_STATE = Path('/var/lib/sig-network')
VPN_CREDENTIALS = Path('/var/lib/sig-vpn-profiles')
PPK_STATE = Path('/var/lib/sig-ppk')
SWANCTL = Path('/etc/swanctl')
REMOTE_LOGGING = Path('/etc/rsyslog.d')
REPO = Path('/etc/yum.repos.d/sig.repo')
KEY = Path('/etc/pki/rpm-gpg/RPM-GPG-KEY-sig')
MAINTENANCE = Path('/run/sig-maintenance')
LOCK = MAINTENANCE / 'lock'
POWER_PENDING = MAINTENANCE / 'power-scheduled'
POWER_REQUEST = Path('/var/lib/sig/power-request.json')
VERSION = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+-[1-9][0-9]*\.el9')
BASE = 'https://shadowtechsolutions.com/wp-json/grid-updates/v1/sig/rpm'
DNF = ['/usr/bin/dnf', '--disablerepo=*', '--enablerepo=sig',
       '--setopt=gpgcheck=1', '--setopt=sig.repo_gpgcheck=1', '--setopt=sig.sslverify=1']


def unique_fields(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError('duplicate field')
        result[key] = value
    return result


def validate_request(fd, uid, now):
    info = os.fstat(fd)
    # The API publishes the complete inode using an exclusive hard link, then
    # removes its private temporary link. Never read before the final link count
    # is one; bound the publication grace period and reject persistent links.
    for unused in range(10):
        if info.st_nlink != 2:
            break
        time.sleep(0.05)
        info = os.fstat(fd)
    if (not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600
            or info.st_uid != uid or info.st_nlink != 1 or info.st_size > 1024):
        raise ValueError('invalid request file')
    data = os.read(fd, 1025)
    if len(data) > 1024:
        raise ValueError('oversized request')
    try:
        request = json.loads(data, object_pairs_hook=unique_fields)
    except (UnicodeError, json.JSONDecodeError):
        raise ValueError('invalid request JSON') from None
    if not isinstance(request, dict) or set(request) != {'action', 'requestedAt', 'requestId', 'version'}:
        raise ValueError('invalid request fields')
    if request['action'] not in ('check', 'install', 'activate'):
        raise ValueError('invalid request action')
    if type(request['requestedAt']) is not int or not 0 <= now - request['requestedAt'] <= 60:
        raise ValueError('invalid request time')
    if not isinstance(request['requestId'], str) or not re.fullmatch(r'[0-9a-f]{32}', request['requestId']):
        raise ValueError('invalid request identity')
    version = request['version']
    if not isinstance(version, str) or (version != '' if request['action'] == 'check' else not VERSION.fullmatch(version)):
        raise ValueError('invalid request version')
    return request


def root_directory(path, mode, gid=0):
    for ancestor in (path,) + tuple(path.parents):
        if ancestor.is_symlink():
            raise ValueError('redirected update directory')
    try:
        path.mkdir(mode=mode)
        os.chown(path, 0, gid)
        os.chmod(path, mode)
    except FileExistsError:
        pass
    info = path.lstat()
    if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_gid != gid or stat.S_IMODE(info.st_mode) != mode:
        raise ValueError('invalid update directory')


def initialize():
    root_directory(MAINTENANCE, 0o700)
    root_directory(SPOOL, 0o750, pwd.getpwnam('sig').pw_gid)
    root_directory(SPOOL / 'claims', 0o700)
    root_directory(SPOOL / 'backups', 0o700)


def claim_request():
    # Rename first so an API-controlled inbox entry cannot be replaced under us.
    directory = Path(tempfile.mkdtemp(prefix='claim-', dir=str(SPOOL / 'claims')))
    claim = directory / 'request.json'
    try:
        os.rename(REQUEST, claim)
        fd = os.open(claim, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
        try:
            return validate_request(fd, pwd.getpwnam('sig').pw_uid, int(time.time()))
        finally:
            os.close(fd)
    finally:
        if claim.is_symlink() or (claim.exists() and not claim.is_dir()):
            claim.unlink()
        if not claim.exists():
            directory.rmdir()


def empty_status():
    return {'state': 'idle', 'installedVersion': '', 'activeVersion': '',
            'availableVersion': None, 'checkedAt': None, 'updateAvailable': False,
            'activationRequired': False, 'requestId': '',
            'message': 'No update check has completed.', 'backupAvailable': False}


def read_status():
    try:
        fd = os.open(STATUS, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    except FileNotFoundError:
        return empty_status()
    try:
        info = os.fstat(fd)
        if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_nlink != 1 or info.st_size > 16384:
            raise ValueError('invalid update status')
        value = json.loads(os.read(fd, 16385))
    finally:
        os.close(fd)
    if not isinstance(value, dict) or set(value) != set(empty_status()):
        raise ValueError('invalid update status fields')
    for key in ('installedVersion', 'activeVersion', 'availableVersion'):
        if value[key] not in ('', None) and (not isinstance(value[key], str) or not VERSION.fullmatch(value[key])):
            raise ValueError('invalid status version')
    return value


def publish(status, **changes):
    status.update(changes)
    content = json.dumps(status, separators=(',', ':'), allow_nan=False) + '\n'
    if len(content.encode()) > 16384:
        raise ValueError('oversized update status')
    fd, temporary = tempfile.mkstemp(prefix='.status-', dir=str(SPOOL))
    try:
        os.fchmod(fd, 0o640)
        os.fchown(fd, 0, pwd.getpwnam('sig').pw_gid)
        with os.fdopen(fd, 'w') as stream:
            stream.write(content)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, STATUS)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


def command(args, timeout=120):
    return subprocess.run(args, check=False, text=True, capture_output=True,
                          timeout=timeout, env={'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LC_ALL': 'C', 'LANG': 'C'})


def trusted_file(path):
    for ancestor in path.parents:
        info = ancestor.lstat()
        if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
            raise ValueError('untrusted repository parent')
    fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    try:
        info = os.fstat(fd)
        if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022 or info.st_nlink != 1 or info.st_size > 65536:
            raise ValueError('untrusted repository file')
        return os.read(fd, 65537).decode('utf-8')
    finally:
        os.close(fd)


def verify_repository():
    config = configparser.ConfigParser(interpolation=None, strict=True)
    config.read_string(trusted_file(REPO))
    if config.defaults() or config.sections() != ['sig']:
        raise ValueError('invalid SIG repository')
    repo = config['sig']
    required = {'baseurl': BASE + '/el9/$basearch/', 'enabled': '1', 'gpgcheck': '1', 'repo_gpgcheck': '1', 'sslverify': '1'}
    if any(repo.get(key, '').strip() != value for key, value in required.items()):
        raise ValueError('signed SIG repository required')
    # Reject other repository selection/trust options rather than silently inherit them.
    if set(repo) - set(required) - {'name', 'gpgkey'}:
        raise ValueError('unsupported repository option')
    key = repo.get('gpgkey', '').strip()
    if key == 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-sig':
        if not trusted_file(KEY).startswith('-----BEGIN PGP PUBLIC KEY BLOCK-----'):
            raise ValueError('invalid SIG public key')
    elif key != BASE + '/RPM-GPG-KEY-sig':
        raise ValueError('unexpected SIG public key')


def versions():
    result = command(['/usr/bin/rpm', '-q', '--qf', '%{VERSION}-%{RELEASE}', 'sig'])
    installed = result.stdout.strip()
    if result.returncode != 0 or not VERSION.fullmatch(installed):
        raise ValueError('cannot identify installed SIG')
    active = (ETC / 'ready').read_text().strip()
    if not VERSION.fullmatch(active):
        raise ValueError('cannot identify active SIG')
    return installed, active


def available_version():
    verify_repository()
    result = command(DNF + ['--quiet', '--refresh', 'check-update', 'sig.x86_64'], timeout=300)
    if result.returncode not in (0, 100):
        raise ValueError('update check failed')
    candidates = []
    for line in result.stdout.splitlines():
        fields = line.split()
        if not fields:
            continue
        if fields[0].startswith('sig.') or (len(fields) == 3 and VERSION.fullmatch(fields[1])):
            if len(fields) != 3 or fields[0] != 'sig.x86_64' or fields[2] != 'sig' or not VERSION.fullmatch(fields[1]):
                raise ValueError('unexpected update result')
            candidates.append(fields[1])
    if result.returncode == 100:
        if len(candidates) != 1:
            raise ValueError('ambiguous update result')
        return candidates[0]
    if candidates:
        raise ValueError('inconsistent update result')
    return None


def backup():
    # The API commits state.json by atomic rename. Read one no-follow inode,
    # checking it remained stable while copied; links are archived, never followed.
    directory = Path(tempfile.mkdtemp(prefix='backup-', dir=str(SPOOL / 'backups')))
    target = directory / 'appliance.tar.gz'
    try:
        with tarfile.open(target, 'w:gz', dereference=False) as archive:
            for root, name in ((ETC, 'etc/sig'), (STATE, 'var/lib/sig')):
                add_backup(archive, root, name)
            if REMOTE_LOGGING.exists():
                for ancestor in (REMOTE_LOGGING,) + tuple(REMOTE_LOGGING.parents):
                    info = ancestor.lstat()
                    if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
                        raise ValueError('untrusted remote logging backup directory')
                for child in sorted(REMOTE_LOGGING.iterdir()):
                    if child.name == '60-sig-remote.conf' or re.fullmatch(r'sig-remote-tls-[a-f0-9]{32}', child.name):
                        add_backup(archive, child, 'etc/rsyslog.d/' + child.name)
            if NETWORK_STATE.exists() or NETWORK_STATE.is_symlink():
                for ancestor in (NETWORK_STATE,) + tuple(NETWORK_STATE.parents):
                    info = ancestor.lstat()
                    if (not stat.S_ISDIR(info.st_mode) or info.st_uid != 0
                            or info.st_mode & (0o077 if ancestor == NETWORK_STATE else 0o022)):
                        raise ValueError('untrusted private routing backup directory')
                # Preserve the journal's encoding/migration intent and any other
                # root recovery evidence. This backup has no automatic restore.
                add_backup(archive, NETWORK_STATE, 'var/lib/sig-network')
            for root, name, private in ((VPN_CREDENTIALS, 'var/lib/sig-vpn-profiles', True),
                                        (PPK_STATE, 'var/lib/sig-ppk', True),
                                        (SWANCTL, 'etc/swanctl', False)):
                if not root.exists() and not root.is_symlink():
                    continue
                for ancestor in (root,) + tuple(root.parents):
                    info = ancestor.lstat()
                    if (not stat.S_ISDIR(info.st_mode) or info.st_uid != 0
                            or info.st_mode & (0o077 if private and ancestor == root else 0o022)):
                        raise ValueError('untrusted private VPN backup directory')
                add_backup(archive, root, name)
        os.chmod(target, 0o600)
        with target.open('rb') as stream:
            os.fsync(stream.fileno())
        return target
    except Exception:
        if target.exists():
            target.unlink()
        directory.rmdir()
        raise


def add_backup(archive, path, name, parent_fd=None):
    leaf = Path(path).name
    if leaf in ('power-request.json', 'update-request.json') or leaf.startswith(('.state-', '.power-request-', '.update-request-')):
        return
    info = os.stat(path, dir_fd=parent_fd, follow_symlinks=False)
    entry = tarfile.TarInfo(name)
    entry.mode = stat.S_IMODE(info.st_mode)
    entry.uid, entry.gid, entry.mtime = info.st_uid, info.st_gid, info.st_mtime
    if stat.S_ISLNK(info.st_mode):
        entry.type, entry.linkname = tarfile.SYMTYPE, os.readlink(path, dir_fd=parent_fd)
        archive.addfile(entry)
    elif stat.S_ISDIR(info.st_mode):
        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_DIRECTORY, dir_fd=parent_fd)
        try:
            opened = os.fstat(fd)
            if (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino):
                raise ValueError('backup source changed')
            entry.type = tarfile.DIRTYPE
            archive.addfile(entry)
            for child in sorted(os.listdir(fd)):
                add_backup(archive, child, name + '/' + child, fd)
        finally:
            os.close(fd)
    elif stat.S_ISREG(info.st_mode):
        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent_fd)
        try:
            opened = os.fstat(fd)
            if (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino):
                raise ValueError('backup source changed')
            with os.fdopen(fd, 'rb', closefd=False) as stream:
                entry.size = opened.st_size
                archive.addfile(entry, stream)
            after = os.fstat(fd)
            # Atomic replacement can unlink this inode and change only ctime;
            # its still-open bytes remain a coherent previous state snapshot.
            if (opened.st_size, opened.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
                raise ValueError('backup source changed')
        finally:
            os.close(fd)
    else:
        raise ValueError('unsupported backup source')


def activate():
    running = []
    try:
        for service in ('sig-api', 'sig-web'):
            if command(['/usr/bin/systemctl', 'is-active', '--quiet', service]).returncode == 0:
                running.append(service)
        result = command(['/usr/bin/systemctl', 'stop', 'sig-web', 'sig-api'])
        if result.returncode:
            raise ValueError('cannot pause management')
        saved = backup()
        result = command(['/usr/bin/sig', 'upgrade', '--backup', str(saved), '--acknowledge-backup'], timeout=300)
        if result.returncode:
            raise ValueError('activation failed')
    finally:
        # sig upgrade owns restart/health/rollback after dispatch. Preflight errors
        # there can still occur before it restarts, so ensure original services run.
        if running:
            result = command(['/usr/bin/systemctl', 'start'] + running)
            if result.returncode:
                raise ValueError('management restart failed')


def process(request, status):
    action = request['action']
    if POWER_PENDING.exists() or POWER_REQUEST.exists() or POWER_REQUEST.is_symlink():
        raise ValueError('power action pending')
    publish(status, state={'check': 'checking', 'install': 'installing', 'activate': 'activating'}[action],
            requestId=request['requestId'], message={'check': 'Checking the signed SIG repository.',
            'install': 'Backing up and installing the selected SIG update.',
            'activate': 'Backing up and activating SIG. Management will reconnect.'}[action])
    installed, active = versions()
    publish(status, installedVersion=installed, activeVersion=active, activationRequired=installed != active)
    if action == 'check':
        available = available_version()
        publish(status, state='idle', availableVersion=available, updateAvailable=available is not None and available != installed,
                checkedAt=int(time.time()), message='Update check completed.')
    elif action == 'install':
        target = request['version']
        if not status['updateAvailable'] or status['availableVersion'] != target or available_version() != target:
            raise ValueError('selected update unavailable')
        backup()
        publish(status, backupAvailable=True)
        result = command(DNF + ['--assumeyes', '--setopt=localpkg_gpgcheck=1', 'upgrade', 'sig-' + target + '.x86_64'], timeout=900)
        if result.returncode:
            raise ValueError('package installation failed')
        installed, current_active = versions()
        if installed != target or current_active != active:
            raise ValueError('unexpected installed version')
        publish(status, state='idle', installedVersion=installed, activeVersion=active, availableVersion=None,
                updateAvailable=False, activationRequired=installed != active,
                message='SIG update installed. Confirm activation to use it.')
    else:
        if request['version'] != installed or installed == active:
            raise ValueError('selected activation unavailable')
        activate()
        installed, active = versions()
        if installed != request['version'] or active != installed:
            raise ValueError('activation did not complete')
        publish(status, state='idle', installedVersion=installed, activeVersion=active,
                activationRequired=False, backupAvailable=True, message='SIG activation completed.')


def main():
    if os.geteuid() != 0:
        return 1
    os.umask(0o077)
    def interrupted(unused_signal, unused_frame):
        raise ValueError('update interrupted')
    signal.signal(signal.SIGTERM, interrupted)
    signal.signal(signal.SIGINT, interrupted)
    initialize()
    status = read_status()
    # flock is root-created and shared with power dispatch. A busy worker leaves
    # the inbox intact; PathExists retriggers after the running oneshot completes.
    fd = os.open(LOCK, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        os.close(fd)
        return 0
    try:
        for index in range(8):
            request = {'action': 'check', 'requestedAt': int(time.time()), 'requestId': '', 'version': ''}
            try:
                if REQUEST.exists() or REQUEST.is_symlink():
                    publish(status, state='checking', requestId='', message='Preparing the requested SIG update action.')
                    request = claim_request()
                elif index:
                    break
                process(request, status)
            except (ValueError, OSError, KeyError, configparser.Error, subprocess.SubprocessError, tarfile.TarError):
                try:
                    installed, active = versions()
                    status.update(installedVersion=installed, activeVersion=active, activationRequired=installed != active)
                except (ValueError, OSError, subprocess.SubprocessError):
                    pass
                publish(status, state='failed', requestId=request['requestId'], message='SIG update action failed. Inspect the updater journal or retry.',
                        backupAvailable=status['backupAvailable'] or any((SPOOL / 'backups').glob('backup-*/appliance.tar.gz')))
                print('sig-update: action failed; inspect repository trust, package availability and appliance health.', file=sys.stderr)
        return 0
    finally:
        os.close(fd)


if __name__ == '__main__':
    try:
        sys.exit(main())
    except (ValueError, OSError, KeyError, subprocess.SubprocessError):
        print('sig-update: unsafe updater state; root inspection required.', file=sys.stderr)
        sys.exit(1)
