#!/bin/bash
#
# SPDX-License-Identifier: GPL-3.0-or-later

LIBDIR=${LIBDIR:-'/usr/share/artools/lib'}
DATADIR=${DATADIR:-'/usr/share/artools'}
SYSCONFDIR=${SYSCONFDIR:-'/etc/artools'}

# shellcheck source=src/lib/pkg/util.sh
source "${LIBDIR}"/pkg/util.sh
# shellcheck source=src/lib/base/message.sh
source "${LIBDIR}"/base/message.sh
# shellcheck source=src/lib/pkg/util/deploy.sh
source "${LIBDIR}"/pkg/util/deploy.sh

#{{{ deploy

add() {
    if pkgfile=$(find_cached_pkgfile "${pkgname}"); then
        msg "Found: %s" "${pkgfile}"
        packages+=("${pkgname}")
        action='add'
        action_args+=(--include-sigs)
        ln -sfv "${pkgfile}"{,.sig} "${repo_path}"/
    fi
}

remove(){
    packages+=("${pkgname}")
    action='remove'
    # pkg removal will be done by a patched repo-remove honoring -R
}

repo_action() {
    local repo_path
    # shellcheck disable=SC2153
    repo_path=${REPOS_ROOT}/${dest_repo}/os/${CARCH}

    local packages=() action func="$1"
    for pkgname in "${passfiles[@]}"; do
        "$func"
    done
    ( cd "${repo_path}" || return
        if [[ -n "${action}" ]]; then
            repo-"${action}" "${action_args[@]}" "${dest_repo}.${db_ext}" "${packages[@]}"
        fi
    )
}

#}}}

load_makepkg_config

db_ext="db.tar.${DBEXT}"

add_pkg=false
rm_pkg=false

cmd=${0##*/}
dest_repo=${cmd#*-}
action_args=(-R)

usage() {
    printf "Usage: %s [options]\n" "${cmd}"
    printf '    -d <dest>          Destination repository\n'
    printf '    -a                 Add package(s) to repository\n'
    printf '    -r                 Remove package(s) from repository\n'
    printf '    -h                 This help\n'
    printf '\n'
    printf '\n'
    exit "$1"
}

opts='arLRhd:'

while getopts "${opts}" arg; do
    case "${arg}" in
        d) dest_repo="$OPTARG" ;;
        a) add_pkg=true; rm_pkg=false ;;
        r) rm_pkg=true; add_pkg=false ;;
        h|?) usage 0 ;;
    esac
done

shift $(( OPTIND - 1 ))

passfiles=("$@")

if [[ -n "${passfiles[*]}" ]]; then
    if ${add_pkg}; then
        repo_action add
    fi
    if ${rm_pkg}; then
        repo_action remove
    fi
fi
