#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import subprocess
import sys

UPDATE_LIST_FILE = '/var/cache/en/update_list'
SMART = '/usr/bin/smart'


def run_smart(args):
    proc = subprocess.Popen(
        [SMART] + args,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    out, err = proc.communicate()
    if isinstance(out, bytes):
        out = out.decode('utf-8', 'replace')
    return proc.returncode, out


def refresh_cache():
    try:
        run_smart(['update'])
    except OSError as exc:
        sys.stderr.write('warning: failed to execute "smart update": %s\n' % exc)


def count_upgradable_packages():
    try:
        returncode, output = run_smart(['newer'])
    except OSError as exc:
        sys.stderr.write('error: failed to execute "smart newer": %s\n' % exc)
        return None

    if returncode != 0:
        sys.stderr.write(
            'warning: "smart newer" exited with code %d; using the output anyway\n' % returncode
        )

    count = 0
    for line in output.splitlines():
        if '|' not in line:
            continue
        columns = [c.strip() for c in line.split('|')]
        if len(columns) == 5 and columns[4].isdigit():
            count += 1
    return count


def sync_update_list(pending_count):
    if pending_count > 0:
        cache_dir = os.path.dirname(UPDATE_LIST_FILE)
        if not os.path.isdir(cache_dir):
            os.makedirs(cache_dir)
        f = open(UPDATE_LIST_FILE, 'w')
        try:
            f.write('3\n')
        finally:
            f.close()
    else:
        if os.path.exists(UPDATE_LIST_FILE):
            os.remove(UPDATE_LIST_FILE)


def main():
    refresh_cache()
    pending_count = count_upgradable_packages()

    if pending_count is None:
        sys.stderr.write(
            'unable to determine pending updates; '
            'update_list left unchanged\n'
        )
        return 1

    sync_update_list(pending_count)
    return 0


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