#!/usr/bin/env python3

import json
import os
import re
import subprocess
import sys


PACMAN_DB = '/var/lib/pacman/'
PACMAN_UPDATES_DB = f'/tmp/checkup-db-{os.getlogin()}/'


def write_output(packages, important_regex):
    n_packages = packages.count('\n')
    if n_packages == 0:
        output_text = 'Up to date'
        output_class = 'good'
        output_alt = 'uptodate'
    else:
        if n_packages == 1:
            output_text = '1 update available'
        else:
            output_text = f'{n_packages} updates available'
        output_class = 'info'
        output_alt = 'available'

    if important_regex and re.search(important_regex, packages,
                                     flags=re.MULTILINE):
        output_class = 'important'

    output = {'text': output_text,
              'class': output_class,
              'alt': output_alt}

    sys.stdout.write(json.dumps(output) + '\n')
    sys.stdout.flush()


def generate_and_update_database():
    if not os.path.isdir(PACMAN_UPDATES_DB):
        os.mkdir(PACMAN_UPDATES_DB)
        os.symlink(os.path.join(PACMAN_DB, 'local'),
                   os.path.join(PACMAN_UPDATES_DB, 'local'))

    subprocess.run(['fakeroot',
                    '--',
                    'pacman',
                    '-Sy',
                    '--dbpath',
                    PACMAN_UPDATES_DB,
                    '--logfile',
                    '/dev/null'],
                   env={'LC_ALL': 'C'},
                   stdout=subprocess.DEVNULL,
                   stderr=subprocess.STDOUT)


def check_updates(important_regex):
    p = subprocess.run(['yay',
                        '-Qu',
                        '--devel',
                        '--dbpath',
                        PACMAN_UPDATES_DB],
                       capture_output=True)
    packages = p.stdout.decode('utf-8')

    write_output(packages, important_regex)


def main(important_regex=None):
    generate_and_update_database()
    check_updates(important_regex)


if __name__ == '__main__':
    if len(sys.argv) > 1:
        main(sys.argv[1])
    else:
        main()
