#!/usr/bin/env python3

import multiprocessing
import os
import sys
import time

import apt_pkg

from apt_listchanges.ALCConfig import ALCConfig
from apt_listchanges.ALCLog import set_debug, debug
from apt_listchanges.ALCSeenDb import SeenDb
from apt_listchanges.DebianFiles import (
    ControlParser,
    ControlStanza,
    InstalledPackage,
)
from apt_listchanges.apt_listchanges import Filterer

CHECKPOINT_EVERY = 10
MAX_LOAD_AVG = multiprocessing.cpu_count()


def main() -> int:
    apt_pkg.init()
    config = ALCConfig()
    config.setup(require_debs=False)
    set_debug(config.debug)
    if not config.save_seen:
        return 0
    seen_db = SeenDb(config.save_seen)
    filterer = Filterer(
        config, seen_db, show_all=False, since=False, latest=10)
    last_checkpoint = time.time()
    status = get_status_db()
    for stanza in status.stanzas:
        if not process_package(config, filterer, stanza):
            continue
        if time.time() - last_checkpoint >= CHECKPOINT_EVERY:
            debug('Checkpointing')
            seen_db.apply_changes()
            loadavg = os.getloadavg()[0]
            while loadavg > MAX_LOAD_AVG:
                debug(f'Load average {loadavg:.2f} > {MAX_LOAD_AVG}, '
                      f'sleeping for {CHECKPOINT_EVERY} seconds')
                time.sleep(CHECKPOINT_EVERY)
                loadavg = os.getloadavg()[0]
            last_checkpoint = time.time()
    seen_db.apply_changes()
    return 0


def get_status_db() -> ControlParser:
    dpkg_status = apt_pkg.config.find_file('Dir::State::status')
    status = ControlParser()
    status.readfile(dpkg_status)
    return status


def process_package(config: ALCConfig, filterer: Filterer,
                    stanza: ControlStanza) -> bool:
    if not stanza.installed:
        return False
    pkg = InstalledPackage(stanza, filterer)
    seen_db = filterer.seen_db
    if seen_db.has_package(pkg.binary):
        return False
    seen_db.add_package(pkg.binary)
    (news, changelog) = pkg.extract_changes_via_installed('both')
    if not (config.no_network or news or changelog or
            pkg.filterer.filtered):
        changelog = pkg.extract_changes_via_apt()
        if changelog:
            debug(f'Fetched changelog for {pkg.binary} from network')
        else:
            debug(f'No network changelog available for {pkg.binary}')
    return True


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