#!/bin/sh
#
# Copyright (C) 2012, 2017, 2020, 2021  Etersoft
# Copyright (C) 2012, 2017, 2020, 2021  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


# Remove repo line from sources.list (delete line)
__apt_delete_repo_line()
{
    local repo="$1"

    local sc="sudocmd"
    [ -z "$quiet" ] || sc="sudorun"

    # touch file only when it is needed
    grep -q -F "$repo" "$APT_SOURCES_LIST" || return
    $sc sed -i -e "\|$(sed_escape "$repo")|d" "$APT_SOURCES_LIST"
}


# like apt-add-repository --remove on deb systems
# For /etc/apt/sources.list: delete lines
# For /etc/apt/sources.list.d/*.list: comment lines via epm repo disable
__epm_removerepo_apt()
{
    local repo="$*"
    [ -n "$repo" ] || fatal "empty repo name"

    if [ -n "$dryrun" ] ; then
        echo "$repo"
        return
    fi

    # main sources.list: delete lines (first, so disable won't touch it)
    __apt_delete_repo_line "$repo"

    # sources.list.d: comment lines instead of deleting
    epm repo disable "^$repo" 2>/dev/null

    return 0
}


__epm_grep_repo_list()
{
    if [ "$1" = "all" ] ; then
        epm --quiet repo list
        return
    fi
    # use --regex for raw regex patterns
    while [ -n "$1" ] ; do
        epm --quiet repo list --regex "$1"
        shift
    done
}

# remove grepped lines
__epm_removerepo_alt_grepremove()
{
    local rl

    rl="$(__epm_grep_repo_list "$@" 2>/dev/null)"
    if [ -z "$rl" ] ; then
        # not an error - repo may be already removed (idempotency)
        [ -n "$verbose" ] && info 'Repo '$*' is not in the repos list'
        return 0
    fi

    echo "$rl" | while read rp ; do
        __epm_removerepo_apt "$rp"
    done
}

__epm_removerepo_alt()
{
    local repo="$*"
    [ -n "$repo" ] || fatal "No such repo or task. Use epm repo remove <regexp|autoimports|archive|tasks|TASKNUMBER>"

    if is_taskarg $repo ; then
        local arg tn
        for arg in $repo ; do
            is_taskarg "$arg" || continue
            tn=$(get_tasknumber_from_arg "$arg")
            __epm_removerepo_alt_grepremove " repo/$tn/" "/tasks/$tn " "/$tn[ /]build/repo"
        done
        return
    fi

    local branch="$(echo "$DISTRVERSION" | tr "[:upper:]" "[:lower:]")"

    case "$1" in
        autoimports)
            info "removing autoimports repo"
            [ -n "$DISTRVERSION" ] || fatal "Empty DISTRVERSION"
            repo="autoimports/$DISTRVERSION"
            __epm_removerepo_alt_grepremove "$repo/"
             ;;
        archive)
            info "removing archive repos"
            __epm_removerepo_alt_grepremove "archive/"
            ;;
        korinf)
            info "removing korinf repo"
            __epm_removerepo_alt_grepremove "Korinf/"
            ;;
        cdroms)
            info "removing cdroms entries"
            __epm_removerepo_alt_grepremove "/^[[:space:]]*rpm[[:space:]]+cdrom:/" "/^cdrom(s)?$/"
            ;;
        tasks)
            info "removing tasks' repos"
            __epm_removerepo_alt_grepremove " repo/[0-9]+/" "/tasks/[0-9]+ " "/[0-9]+[ /]build/repo"
            ;;
        task)
            shift
            __epm_removerepo_alt_grepremove " repo/$1/" "/tasks/$1 " "/$1[ /]build/repo"
            ;;
        all)
            info "removing all repos"
            __epm_removerepo_alt_grepremove "all"
            ;;
        -*)
            fatal "epm removerepo: no options are supported"
            ;;
        *)
            if echo "$*" | grep -q "^rpm" ; then
                __epm_removerepo_apt "$*"
            else
                info "removing with grep by '$*'"
                # TODO: switch to $@ and use epm repo remove instead of __epm_removerepo_alt_grepremove
                __epm_removerepo_alt_grepremove "$*"
            fi
            ;;
    esac

}

epm_removerepo()
{

# Handle copr/owner/project syntax for Fedora/RHEL
case "$1" in
    copr/*)
        local owner_project="$(echo "$1" | sed 's|^copr/||')"
        case $PMTYPE in
            dnf-rpm|dnf5-rpm)
                sudocmd dnf copr disable "$owner_project"
                ;;
            yum-rpm)
                sudocmd yum copr disable "$owner_project"
                ;;
            *)
                fatal "Copr repos are only supported on Fedora/RHEL systems (dnf/yum)"
                ;;
        esac
        return
        ;;
esac

case $BASEDISTRNAME in
    "alt")
        __epm_removerepo_alt "$@"
        return
        ;;
    "astra")
        # handle "all" and pattern-based removal
        case "$1" in
            all)
                info "removing all repos"
                __epm_removerepo_alt_grepremove "all"
                ;;
            *)
                __epm_removerepo_apt "$@"
                ;;
        esac
        return
        ;;
esac;

case $PMTYPE in
    apt-dpkg)
        local files
        files="$(__find_deb822_files_by_pattern "$1")"
        if [ -n "$files" ] ; then
            assure_root
            echo "$files" | while read f ; do
                __deb822_remove "$f"
            done
        else
            assure_exists apt-add-repository software-properties-common
            # FIXME: it is possible there is troubles to pass the args
            sudocmd apt-add-repository --remove "$*"
            info "Check file /etc/apt/sources.list if needed"
        fi
        ;;
    aptitude-dpkg)
        info "You need remove repo from /etc/apt/sources.list"
        ;;
    yum-rpm)
        assure_exists yum-utils
        sudocmd yum-config-manager --disable "$@"
        ;;
    dnf-rpm)
        repo_file_name=$(env LC_ALL=C dnf repoinfo "$@" 2>/dev/null | sed -n 's/^Repo-filename\s*:\s*//p')
        sudocmd rm "$repo_file_name"
        ;;
    dnf5-rpm)
        repo_file_name=$(env LC_ALL=C dnf repoinfo "$@" 2>/dev/null | sed -n 's/^Config file\s*:\s*//p')
        sudocmd rm "$repo_file_name"
        ;;
    urpm-rpm)
        if [ "$1" = "all" ] ; then
            sudocmd urpmi.removemedia -av
            return
        fi
        sudocmd urpmi.removemedia "$@"
        ;;
    zypper-rpm)
        sudocmd zypper removerepo "$@"
        ;;
    emerge)
        sudocmd layman "-d$1"
        ;;
    pacman)
        info "You need remove repo from /etc/pacman.conf"
        ;;
    npackd)
        sudocmd npackdcl remove-repo --url="$*"
        ;;
    winget)
        sudocmd winget source remove "$@"
        ;;
    eopkg)
        sudocmd eopkg remove-repo "$@"
        ;;
    stplr)
        sudocmd stplr repo remove "$@"
        ;;
    pisi)
        sudocmd pisi remove-repo "$@"
        ;;
    slackpkg)
        info "You need remove repo from /etc/slackpkg/mirrors"
        ;;
    *)
        fatal 'Have no suitable command for $PMTYPE in epm_removerepo()'
        ;;
esac

}
