#!/bin/sh
#
# Copyright (C) 2023  Etersoft
# Copyright (C) 2023  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/>.
#

load_helper epm-sh-altlinux
load_helper epm-sh-repo


__epm_repoenable_alt()
{
    assure_root
    local rl
    # ^rpm means full string
    if rhas "$1" "\^rpm" ; then
        rl="$(echo "$1" | sed -e 's|\^||')"
        # check if this exact line exists as a comment
        if ! grep -q -E "^[[:space:]]*#[[:space:]]*$(sed_escape "$rl")" $APT_ALL_SOURCES_LIST 2>/dev/null ; then
            return 1
        fi
    else
        rl="$( epm --quiet repolist --all 2>/dev/null | grep -F "$1" | sed -e 's|[[:space:]]*#[[:space:]]*||' )"
        [ -z "$rl" ] && warning 'Can'\''t find commented $1 in the repos (see # epm repolist output)' && return 1
    fi
    local apt_lists
    apt_lists="$(filter_glob_list $APT_ALL_SOURCES_LIST)"
    [ -z "$apt_lists" ] && return 0
    echo "$rl" | while read rp ; do
        [ -n "$dryrun" ] && message 'will uncomment $rp' && continue
        sed -i -e "s|^[[:space:]]*#[[:space:]]*\($(sed_escape "$rp")\)|\1|" $apt_lists
    done
}


epm_repoenable()
{

case $PMTYPE in
    apt-rpm|apm-rpm)
        __epm_repoenable_alt "$@"
        ;;
    apt-dpkg|aptitude-dpkg)
        local files
        files="$(__find_deb822_files_by_pattern "$1")"
        if [ -n "$files" ] ; then
            assure_root
            echo "$files" | while read f ; do
                info "Enabling $f ..."
                __deb822_enable "$f"
            done
        else
            __epm_repoenable_alt "$@"
        fi
        ;;
    yum-rpm)
        docmd yum repolist $verbose
        [ -n "$verbose" ] || info "Use --verbose if you need detail information."
        ;;
    dnf-rpm)
        sudocmd dnf config-manager --disable $verbose "$@"
        ;;
    dnf5-rpm)
        sudocmd dnf config-manager setopt "$@.enabled=1"
        ;;
    eoget)
        docmd eoget enable-repo "$@"
        ;;
    pisi)
        docmd pisi enable-repo "$@"
        ;;
    *)
        fatal 'Have no suitable command for $PMTYPE in epm_repoenable()'
        ;;
esac

}
