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


__replace_text_in_alt_repo()
{
    local i
    for i in /etc/apt/sources.list /etc/apt/sources.list.d/*.list ; do
        [ -s "$i" ] || continue
        # TODO: don't change file if untouched
        #grep -q -- "$1" "$i" || continue
        regexp_subst "$1" "$i"
    done
}

__repofix_check_vendor()
{
    local i
    for i in /etc/apt/vendors.list.d/*.list; do
        [ -e "$i" ] || continue
        grep -q "^simple-key \"$1\"" $i && return
    done
    return 1
}

__repofix_filter_vendor()
{
    local br="$1"
    br="$(echo "$br" | sed -e "s|\..*||")"
    case $br in
        c8*)
            br="cert8"
            ;;
        c9*)
            br="cert8"
            ;;
        c10*)
            br="cert8"
            ;;
        Sisyphus)
            br="alt"
            ;;
    esac
    echo "$br"
}


__replace_alt_version_in_repo()
{
    local i
    #echo "Upgrading $DISTRNAME from $1 to $2 ..."
    epm --quiet repo list | sed -E -e "s|($1)|{\1}->{$2}|g" | grep -E --color -- "$1"
    # ask and replace only we will have changes
    if epm --quiet repo list | grep -E -q -- "$1" ; then
        __replace_text_in_alt_repo "/^ *#/! s!$1!$2!g"
    fi
}

__alt_replace_sign_name()
{
    local TO="$1"
    __replace_text_in_alt_repo "/^ *#/! s!\[alt\]!$TO!g"
    __replace_text_in_alt_repo "/^ *#/! s!\[sisyphus\]!$TO!g"
    __replace_text_in_alt_repo "/^ *#/! s!\[updates\]!$TO!g"
    __replace_text_in_alt_repo "/^ *#/! s!\[cert[789]\]!$TO!g"
    __replace_text_in_alt_repo "/^ *#/! s!\[[tcp][1-3]?[0-9][.f]?[0-9]?\]!$TO!g"
}

__alt_repofix()
{
    local TO="$1"
    epm --quiet repo fix >/dev/null
    if [ -n "$TO" ] ; then
        # TODO: switch it in repo code
        TO="$(__repofix_filter_vendor "$TO")"
        __alt_replace_sign_name "[$TO]"
    fi
}

__alt_branch_reg='[tcp][1-3]?[0-9][.f]?[0-9]?'

#__switch_repo_to()
epm_reposwitch()
{
    local TO="$1"
    [ -n "$TO" ] || fatal "run repo switch with arg (p9, p10, Sisyphus)"
    [ "$TO" = "sisyphus" ] && TO="Sisyphus"

    case "$TO" in
        --help)
            message "Run with --list to get all possible targets"
            return
            ;;
        --list)
            [ -z "$quiet" ] && message "Possible repo switch targets:"
            echo "p8 p9 p10 p11 c8 c9 c10f1 c10f2 Sisyphus"
            return
            ;;
        -*)
            fatal 'Unknown option $TO'
            ;;
    esac

    if [ "$TO" = "Sisyphus" ] ; then
        __replace_alt_version_in_repo "$__alt_branch_reg/branch/" "$TO/"
    else
        echo "$TO" | grep -q -E "${__alt_branch_reg}" || fatal 'Unsupported target form $TO. Use --list to get all targets.'
        __replace_alt_version_in_repo "Sisyphus/" "$TO/branch/"
        __replace_alt_version_in_repo "$__alt_branch_reg/branch/" "$TO/branch/"
    fi

    __alt_repofix "$TO"

    # TODO: improve for c10f1?
    case $TO in
        "p10"|"p11"|"Sisyphus")
            rm -fv /etc/rpm/macros.d/{p10,p11} 

            [ "$TO" = "Sisyphus" ] && TO="sisyphus"
            
            echo "%_priority_distbranch $TO" >/etc/rpm/macros.d/priority_distbranch
            ;;
        *)
            rm -fv /etc/rpm/macros.d/{p10,p11,priority_distbranch}
            ;;
    esac
    #epm repo list
}


# source-list vendor path
# example: /etc/apt/source.list p7 ALTLinux\/Sisyphus
__try_fix_apt_source_list()
{
    local list="$1"
    local br="$(__repofix_filter_vendor "$2")"
    local path="$3"
    # FIXME: masked grep: предупреждение: stray \ before /
    if grep -q -e "^[^#].*$path" $list 2>/dev/null ; then
        if __repofix_check_vendor $br ; then
            regexp_subst "/$path/s/^rpm[[:space:]]*([fhr])/rpm [$br] \1/" $list
        else
            warning "Skip set $br vendor key (it is missed) for $list"
            regexp_subst "/$path/s/^rpm[[:space:]]*\[$br\][[:space:]]*([fhr])/rpm \1/" $list
        fi
    fi
}

__fix_alt_sources_list()
{
    # for beauty spaces
    local SUBST_ALT_RULE1='s!^(.*)[/ ](ALTLinux|LINUX\@Etersoft)[/ ]*(Sisyphus)[/ ](x86_64|i586|x86_64-i586|noarch|aarch64) !\1 \2/\3/\4 !gi'
    local SUBST_ALT_RULE2='s!^(.*)[/ ](ALTLinux|LINUX\@Etersoft)[/ ]*('$__alt_branch_reg'[/ ]branch)[/ ](x86_64|i586|x86_64-i586|noarch|aarch64) !\1 \2/\3/\4 !gi'
    local i

    for i in "$@" ; do
        [ -s "$i" ] || continue
        #perl -i.bak -pe "$SUBST_ALT_RULE" $i
        # TODO: only for uncommented strings
        #sed -i -r -e "$SUBST_ALT_RULE" $i
        regexp_subst "/^ *#/! s| pub|/pub|" $i
        regexp_subst "/^ *#/! s| distributions|/distributions|" $i
        regexp_subst "/^ *#/! $SUBST_ALT_RULE1" $i
        regexp_subst "/^ *#/! $SUBST_ALT_RULE2" $i

        # don't restore repo sign
        continue

        # Sisyphus uses 'alt' vendor key
        __try_fix_apt_source_list $i alt "ALTLinux\/Sisyphus"
        __try_fix_apt_source_list $i etersoft "Etersoft\/Sisyphus"

        # skip branch replacement for ALT Linux Sisyphus
        [ "$DISTRVERSION" = "Sisyphus" ] && continue

        # add signs for branches
        __try_fix_apt_source_list $i $DISTRVERSION "ALTLinux\/$DISTRVERSION\/branch"
        __try_fix_apt_source_list $i etersoft "Etersoft\/$DISTRVERSION\/branch"
    done
}


__subst_with_repo_url()
{
    local NURL="$2"
    echo "$1" | sed \
        -e "s|//mirror.yandex.ru/* altlinux|$NURL|" \
        -e "s|//ftp.altlinux.org/pub/distributions/* ALTLinux|$NURL|" \
        -e "s|//ftp.basealt.ru/pub/distributions/* ALTLinux|$NURL|" \
        -e "s|//update.altsp.su/pub/distributions/* ALTLinux|$NURL|" \
        -e "s|//ftp.etersoft.ru/pub/* ALTLinux|$NURL|" \
        -e "s|//mirror.datacenter.by/pub/* ALTLinux|$NURL|" \
        -e "s|//mirror.truenetwork.ru/* altlinux|$NURL|" \
        -e "s|//mirror.cs.msu.ru/* alt|$NURL|" \
        -e "s|//download.etersoft.ru/pub/* ALTLinux|$NURL|" \
        -e "s|//mirror.eterfund.org/download.etersoft.ru/pub/* ALTLinux|$NURL|"
}

__change_repo()
{
    local REPLTO="$1"
    local NN
    epm --quiet repo list | grep -v "file:/" | while read nn ; do
        NN="$(__subst_with_repo_url "$nn" "$REPLTO")"
        [ "$NN" = "$nn" ] && continue
        epm addrepo "$NN" && epm removerepo "$nn" || return 1
    done
}


__epm_repochange_alt()
{
    case "$1" in
        "--list")
            [ -z "$quiet" ] && message "Possible targets:"
            echo "etersoft datacenter.by truenetwork msu eterfund.org yandex basealt altlinux.org"
            ;;
        "etersoft")
            __change_repo "//download.etersoft.ru/pub ALTLinux"
            ;;
        "datacenter.by")
            __change_repo "//mirror.datacenter.by/pub ALTLinux"
            ;;
        "truenetwork")
            __change_repo "//mirror.truenetwork.ru altlinux"
            ;;
        "msu")
            __change_repo "//mirror.cs.msu.ru alt"
            ;;
        "eterfund.org")
            __change_repo "//mirror.eterfund.org/download.etersoft.ru/pub ALTLinux"
            ;;
        "yandex")
            __change_repo "//mirror.yandex.ru altlinux"
            ;;
        "basealt")
            __change_repo "//ftp.basealt.ru/pub/distributions ALTLinux"
            ;;
        "altlinux.org")
            __change_repo "//ftp.altlinux.org/pub/distributions ALTLinux"
            ;;
        *)
            fatal 'Unsupported change key $1'
            ;;
    esac
}


epm_repochange()
{
    [ "$1" = "--help" ] && message "Use --list to get all possible targets" && return
    [ "$1" = "--list" ] || epm_repofix
    case $BASEDISTRNAME in
        "alt")
            __epm_repochange_alt "$@"
            ;;
         *)
            fatal 'Repo change Unsupported for $BASEDISTRNAME'
            ;;
    esac
}


epm_repofix()
{

case $BASEDISTRNAME in
    "alt")
        [ -n "$quiet" ] || docmd epm repo list
        assure_root

        __fix_alt_sources_list /etc/apt/sources.list
        __fix_alt_sources_list /etc/apt/sources.list.d/*.list

        [ -n "$quiet" ] || docmd epm repo list
        return
        ;;
esac

case $PMTYPE in
#    apt-rpm)
#        ;;
#    yum-rpm|dnf-rpm)
#        ;;
    *)
        fatal 'Have no suitable command for $PMTYPE in epm_repofix()'
        ;;
esac

}

epm_repoclean()
{
    epm repo remove tasks
    epm repo remove cdroms
}
