#!/bin/sh
#
# Copyright (C) 2025  Etersoft
# Copyright (C) 2025  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

epm_db_help()
{
    message "epm db - package database operations"
            get_help HELPCMD $SHAREDIR/epm-db
}

__epm_check_lock()
{
    local lock_file="$1"
    [ -f "$lock_file" ] || return 1
    fuser -s "$lock_file" 2>/dev/null
}

__epm_check_apt_lock()
{
    # ALT Linux apt lock
    __epm_check_lock /var/lib/apt/lists/lock && return 0
    # Debian/Ubuntu dpkg lock
    __epm_check_lock /var/lib/dpkg/lock-frontend && return 0
    return 1
}

__epm_check_rpm_lock()
{
    __epm_check_lock /var/lib/rpm/.rpm.lock
}

epm_db_locked()
{
    local locked=
    case $PMTYPE in
        apt-*)
            if __epm_check_apt_lock ; then
                info "apt database is locked"
                locked=1
            fi
            ;;
    esac

    case $PMTYPE in
        *-rpm|*-dnf)
            if __epm_check_rpm_lock ; then
                info "rpm database is locked"
                locked=1
            fi
            ;;
    esac

    if [ -n "$locked" ] ; then
        return 0
    fi

    info "Package database is not locked"
    return 1
}

epm_db()
{
    local cmd="$1"
    shift

    case "$cmd" in
        -h|--help|help|"")           # HELPCMD: print this help
            epm_db_help
            ;;
        fix)                         # HELPCMD: fix the package database
            load_helper epm-check
            epm_check "$@"
            ;;
        locked)                      # HELPCMD: check if the package database is locked
            epm_db_locked
            ;;
        *)
            fatal "Unknown command '$cmd'. Use epm db --help for help."
            ;;
    esac
}
