#!/bin/bash

# Passwordless, fixed-scope maintenance actions for mx-packageinstaller (pacman
# backend). Installed as /usr/lib/mx-packageinstaller/mxpi-maintenance, same as the
# apt variant (scripts/mxpi-maintenance) -- see that file for the reasoning behind
# what belongs here (narrow, non-trust-mutating actions) versus in mxpi-lib
# (auth_admin_keep-gated, for anything that adds trusted sources or enables services).

run_helper() {
    local candidate
    for candidate in /usr/libexec/mx-packageinstaller/helper /usr/lib/mx-packageinstaller/helper; do
        if [[ -x "$candidate" ]]; then
            "$candidate" "$@"
            return $?
        fi
    done
    echo "mxpi-maintenance: helper is missing" >&2
    return 1
}

if [[ $# -ge 2 && "$1" == "--marker" ]]; then
    marker="$2"
    if ! run_helper create-marker "$marker"; then
        echo "mxpi-maintenance: could not create authentication marker" >&2
        exit 1
    fi
    shift 2
fi

repo_sync() {
    # Refresh the catalog without advancing the system database ahead of installed packages.
    local db=/run/mx-packageinstaller-pacman
    install -d -m 0755 -- "$db" && pacman --dbpath "$db" --logfile /dev/null -Sy --noconfirm
}

main() {
case "$1" in
    repo_sync)
        repo_sync;;
    copy_log)
        run_helper archive-log;;
    *)
        echo "mxpi-maintenance: unknown action '$1'" >&2
        exit 1;;
esac
}

main "$@"
