#!/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
}

update_dbg() {
    local rmp
    rmp=${pkgname%"${PKGEXT}"}
    rmp=${rmp%-*}
    rmp=${rmp%-*}
    rm -fv "${PKGDEST_DBG}/${rmp}"*
    if pkgfile=$(find_cached_pkgfile "${pkgname}"); then
        msg "Found: %s" "${pkgfile}"
        ln -sfv "${pkgfile}" "${PKGDEST_DBG}"/
    fi
}

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
    if ! "${dbg_pkg}"; then
        ( cd "${repo_path}" || return
            if [[ -n "${action}" ]]; then
                repo-"${action}" "${action_args[@]}" "${dest_repo}.${db_ext}" "${packages[@]}"
            fi
        )
    fi
}

#}}}

load_makepkg_config

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

add_pkg=false
rm_pkg=false
dbg_pkg=false

cmd=${0##*/}
dest_repo=world #${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 '    -u                 Update debug repository\n'
    printf '    -h                 This help\n'
    printf '\n'
    printf '\n'
    exit "$1"
}

opts='uarhd:'

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 ;;
        u) dbg_pkg=true ;;
        h|?) usage 0 ;;
    esac
done

shift $(( OPTIND - 1 ))

passfiles=("$@")

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