#!/usr/bin/python3
""" Add packages to a repository.

Functions:
==========
* add_pkgfiles(cachedir, pkgs)
* repo_add(db, pkgs, opts=None)
"""

import argparse
import logging
import pathlib
import shutil
import sys

import packaging_scripts.pacmanconf as pacmanconf
import packaging_scripts.pkgfiles as pkgfiles
import packaging_scripts.repos as repos

# ========== Constants ==========
REPO_ADD_CMD = '/usr/bin/repo-add'
DB_EXT = 'db.tar.xz'
LOGFORMAT = '==> %(levelname)s %(message)s'

# ========== Exit codes ==========
E_NOFILESERR = 1
E_REPO_ADDERR = 2

# ========== Logging setup ==========
console_formatter = logging.Formatter(LOGFORMAT)
syslog = logging.getLogger('packaging_scripts')
syslog.setLevel(logging.DEBUG)

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(console_formatter)

syslog.addHandler(console_handler)


# ========== Functions ==========
def add_pkgfile(pkg, cachedir):
    """Add package file to the repository directory.

    :param pkg: path of package to add
    :type pkg: str, bytes, or path-like object
    :param cachedir: cache directory to move package to
    :type cachedir: str, bytes, or path-like object
    """
    syslog.info(f"Adding {pkg} to {cachedir}")

    pkgpath = pathlib.Path(pkg)
    cachepath = pathlib.Path(cachedir)
    shutil.move(str(pkgpath), str(cachepath.joinpath(pkg.name)))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--sign',
                        dest='opts',
                        action='append_const',
                        const='--sign',
                        help='sign repository file')
    parser.add_argument('-v', '--verbose',
                        action='store_true',
                        help='increase script verbosity')
    parser.add_argument('repository',
                        choices=pacmanconf.list_configured_repos(),
                        help='the repository to operate on',
                        metavar='repo')
    parser.add_argument('packages',
                        default=None,
                        nargs='*',
                        help='packages to add')

    args = parser.parse_args()
    repo = args.repository
    pkgs = args.packages
    opts = args.opts

    cachedir = f"/var/cache/pacman/{repo}"
    # this assumes that the db file for the repo
    # has the same name as that repo
    db = f"{cachedir}/{repo}.{DB_EXT}"

    if args.verbose:
        stdout_handler.setLevel(logging.DEBUG)

    if pkgs:
        pkg_tarballs = pkgs
        sigfiles = []
    else:
        pkg_tarballs = list(pkgfiles.get_pkgfiles())
        sigfiles = list(pkgfiles.get_pkgfiles(signatures_only=True))

    if not pkg_tarballs:
        syslog.critical('No package tarballs have been found, exiting')
        exit(E_NOFILESERR)

    try:
        repos.repo_add('add', db, *pkg_tarballs, opts=opts)
    except repos.RepoAddError as e:
        syslog.error(e)
        exit(E_REPO_ADDERR)

    for pkg_tarball in pkg_tarballs:
        add_pkgfile(pkg_tarball, cachedir)

    for sigfile in sigfiles:
        add_pkgfile(sigfile, cachedir)