#!/usr/bin/env python3

"""
## pkg


Manage BSD packages and repositories. Note that BSD package names are case-sensitive.
"""

from . import _run_pyinfra, PyInfraFailed, PyInfraResults
from typing import Optional, List
from ..internals import task, TemplateStr, Return


@task
def packages(packages=None, present=True, pkg_path=None):
    """
    Install/remove/update pkg packages. This will use ``pkg ...`` where available
    (FreeBSD) and the ``pkg_*`` variants elsewhere.

    + packages: list of packages to ensure
    + present: whether the packages should be installed
    + pkg_path: the PKG_PATH environment variable to set

    pkg_path:
        By default this is autogenerated as follows (tested/working for OpenBSD):
        ``http://ftp.<OS>.org/pub/<OS>/<VERSION>/packages/<ARCH>/``. Note that OpenBSD's
        official mirrors only hold the latest two versions packages.

        NetBSD/FreeBSD helpfully use their own directory structures, so the default won't
        work.

    **Example:**

    .. code:: python

        pkg.packages(
            name="Install Vim and Vim Addon Manager",
            packages=["vim-addon-manager", "vim"],
        )
    """
    operargs = {
        "packages": repr(packages),
        "present": repr(present),
        "pkg_path": repr(pkg_path),
    }

    result = _run_pyinfra(
        "from pyinfra.operations import pkg", "pkg.packages", operargs
    )

    if result.errors:
        return Return(failure=True)
    return Return(changed=result.changed != 0)
