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

load_helper epm-sh-altlinux


# allowed files too
__epm_get_file_from_url()
{
    local url="$1"
    local tmpfile
    tmpfile=$(mktemp -u) || fatal
    remove_on_exit $tmpfile
    eget -O "$tmpfile" "$url" >/dev/null
    echo "$tmpfile"
}

__epm_altgpg()
{
    sudocmd gpg --no-default-keyring --keyring /usr/lib/alt-gpgkeys/pubring.gpg "$@"
}

__epm_importgpg_altlinux()
{
    local res
    local url="$1"
    local tmpfile=$(__epm_get_file_from_url "$url") || fatal
    # just always try import
    __epm_altgpg --import $tmpfile
    res=$?
    rm $tmpfile
    return $res
}


# gpg --with-colons --with-fingerprint 1.gpg
# pub:-:4096:1:617AB978CB849A76:2022-10-25:::-:Angie (Signing Key) <devops@tech.wbsrv.ru>:
# fpr:::::::::EB8EAF3D4EF1B1ECF34865A2617AB978CB849A76:
__epm_altgpg_get_fingerprint()
{
    __epm_altgpg --with-colons --with-fingerprint "$1" | grep fpr | rev | cut -d":" -f2 | rev
}

__epm_altgpg_get_comment()
{
    __epm_altgpg --with-colons --with-fingerprint "$1" | grep pub | rev | cut -d":" -f2 | rev
}

# args: [name] [url] [fingerprint] [comment] [name]
# actuals:
#   url
#   name url
#   name url fingerprint comment
#   fingerprint comment
__epm_addkey_altlinux()
{
    local name
    local url="$1"
    shift
    if is_url "$url" ; then
        name="$(basename "$url" .gpg)"
    else
        name="$url"
        url="$1"
        shift
    fi

    local fingerprint
    if is_url "$url" ; then
        fingerprint="$1"
        shift
    else
        fingerprint="$url"
        url=""
    fi

    local comment="$1"
    # compat
    [ -n "$2" ] && name="$2"

    local tmpfile=''

    if [ -n "$url" ] ; then
        tmpfile=$(__epm_get_file_from_url "$url") || fatal
        [ -s "$tmpfile" ] || fatal 'Can'\''t download $url'
        # /usr/lib/alt-gpgkeys belongs to alt-gpgkeys package and is replaced on its update,
        # apt-gpgkeys-pki merges it with the keys from /etc/pki/apt-gpg/sources (APT::GPG::Homedir)
        epm install --skip-installed apt-gpgkeys-pki
        if [ -x /usr/bin/apt-gpgkeys ] ; then
            sudocmd mkdir -p /etc/pki/apt-gpg/sources
            sudocmd cp $tmpfile /etc/pki/apt-gpg/sources/$name.gpg || fatal
            sudocmd chmod 644 /etc/pki/apt-gpg/sources/$name.gpg
            sudocmd /usr/bin/apt-gpgkeys update || fatal
        else
            warning 'apt-gpgkeys-pki is not installed, the key is imported to /usr/lib/alt-gpgkeys and will be lost on alt-gpgkeys update'
            __epm_altgpg --import $tmpfile
        fi
    fi

    if [ ! -s /etc/apt/vendors.list.d/$name.list ] ; then

        if [ -z "$fingerprint" ] || [ -z "$comment" ] ; then
            [ -n "$url" ] || fatal "can't get fingerprint and comment from url, missed url"
            [ -n "$tmpfile" ] || tmpfile=$(__epm_get_file_from_url "$url") || fatal
            fingerprint="$(__epm_altgpg_get_fingerprint "$tmpfile")"
            comment="$(__epm_altgpg_get_comment "$tmpfile")"
        fi

        [ -n "$fingerprint" ] || fatal "missed fingerprint"
        [ -n "$comment" ] || fatal "missed comment"

        cat << EOF | sudorun tee /etc/apt/vendors.list.d/$name.list
simple-key "$name" {
        FingerPrint "$fingerprint";
        Name "$comment";
}
EOF
    fi

}


# convert binary gpg key file to armored one in place (rpm --import accepts armored keys only)
__epm_dearmor_to_armor()
{
    local file="$1"
    grep -q -- "-----BEGIN PGP PUBLIC KEY BLOCK-----" "$file" && return
    assure_exists gpg gnupg2
    local tmpdir
    tmpdir=$(mktemp -d) || fatal
    remove_on_exit $tmpdir
    a='' gpg --homedir $tmpdir --quiet --import "$file" 2>/dev/null || fatal 'Can'\''t import key from $file'
    a='' gpg --homedir $tmpdir --export --armor >"$file" 2>/dev/null || fatal
}

# put key to /etc/pki/rpm-gpg and import it to rpm db (dnf on ALT)
# args: same as __epm_addkey_altlinux
__epm_addkey_alt_dnf()
{
    local name
    local url="$1"
    shift
    if is_url "$url" ; then
        name="$(basename "$url" | sed -e 's/\.\(gpg\|asc\|key\)$//')"
    else
        name="$url"
        url="$1"
        shift
    fi
    # compat
    [ -n "$3" ] && name="$3"

    is_url "$url" || { warning 'Skipping key $name: there is no key URL' ; return 0 ; }

    local target="/etc/pki/rpm-gpg/RPM-GPG-KEY-$name"
    local tmpfile
    tmpfile=$(__epm_get_file_from_url "$url") || fatal
    [ -s "$tmpfile" ] || fatal 'Can'\''t download $url'
    __epm_dearmor_to_armor $tmpfile
    chmod 644 $tmpfile
    sudocmd mkdir -p /etc/pki/rpm-gpg
    sudocmd cp $tmpfile "$target"
    sudocmd rpm --import "$target"
}

__epm_addkey_alpine()
{
    local name
    local url="$1"
    shift
    if is_url "$url" ; then
        name="$(basename "$url" .rsa)"
    else
        name="$url"
        url="$1"
        shift
    fi

    local target="/etc/apk/keys/$name.rsa"

    [ -s $target ] && return

    local tmpfile=$(__epm_get_file_from_url $url) || fatal
    sudocmd cp $tmpfile $target
}


# [name] url gpgkeyurl comment
__epm_addkey_dnf()
{
    local name
    local url="$1"
    shift
    if is_url "$url" ; then
        name="$(basename "$url" .gpg)"
    else
        name="$url"
        url="$1"
        shift
    fi
    local gpgkeyurl="$1"
    local nametext="$2"
    # compat
    [ -n "$3" ] && name="$3"

    # TODO: missed name, nametext, gpgkeyurl (disable gpgcheck=1)

    local target="/etc/yum.repos.d/$name.repo"
    [ -s $target ] && return

    local tmpfile
    tmpfile=$(mktemp) || fatal
    remove_on_exit $tmpfile
    cat >$tmpfile <<EOF
[$name]
name=$nametext
baseurl=$url
gpgcheck=1
enabled=1
gpgkey=$gpgkeyurl
EOF
    #epm repo add $tmpfile
    chmod 644 $tmpfile
    sudocmd cp $tmpfile $target
}


__epm_addkey_deb()
{
    local name
    local url="$1"
    shift
    if is_url "$url" ; then
        name="$(basename "$url" .gpg)"
    else
        name="$url"
        url="$1"
        shift
    fi
    local fingerprint="$1"
    local comment="$2"
    # compat
    [ -n "$3" ] && name="$3"

    # FIXME: check by GPG PUBKEY
    [ -s /etc/apt/trusted.gpg.d/$name.gpg ] && return

    if [ -z "$fingerprint" ] ; then
        local tmpfile=$(__epm_get_file_from_url $url) || fatal
        if cat $tmpfile | head -n3 | grep -- "-----BEGIN PGP PUBLIC KEY BLOCK-----" ; then
            # This is a GnuPG extension to OpenPGP
            cat $tmpfile | a= gpg --dearmor >$tmpfile
        fi
        sudocmd apt-key add $tmpfile
#
#        if [ ! -f /etc/apt/trusted.gpg.d/$name.gpg ]; then
#                epm tool eget -q -O /etc/apt/trusted.gpg.d/$name.gpg https://example.com/$name.gpg > /dev/null
#                chmod 0644 /etc/apt/trusted.gpg.d/$name.gpg
#        fi

        return
    fi
    sudocmd apt-key adv --keyserver "$url" --recv "$fingerprint"
}

epm_importgpg()
{

if [ "$1" = "-h" ] || [ "$1" = "--help" ] || [ -z "$1" ] ; then
    message "Usage: $ epm repo importgpg <url>"
    return
fi

# initialize here
remove_on_exit

case $BASEDISTRNAME in
    "alt")
        if [ "$PMTYPE" = "dnf-rpm" ] || [ "$PMTYPE" = "dnf5-rpm" ] ; then
            local tmpfile
            tmpfile=$(__epm_get_file_from_url "$1") || fatal
            __epm_dearmor_to_armor $tmpfile
            sudocmd rpm --import $tmpfile
            return
        fi
        __epm_importgpg_altlinux "$@"
        return
        ;;
esac

}




epm_addkey()
{

if [ "$1" = "-h" ] || [ "$1" = "--help" ] || [ -z "$1" ] ; then
    message "Usage: $ epm repo addkey [name] [url] [fingerprint/gpgkey] [comment/name]"
    return
fi

# initialize here
remove_on_exit

case $BASEDISTRNAME in
    "alt")
        if [ "$PMTYPE" = "dnf-rpm" ] || [ "$PMTYPE" = "dnf5-rpm" ] && ! __alt_dnf_uses_apt_sources ; then
            __epm_addkey_alt_dnf "$@"
            return
        fi
        __epm_addkey_altlinux "$@"
        return
        ;;
    "alpine")
        __epm_addkey_alpine "$@"
        return
        ;;
esac

case $PMTYPE in
    apt-dpkg)
        __epm_addkey_deb "$@"
        ;;
    dnf-*|dnf5-*|yum-*)
        __epm_addkey_dnf "$@"
        ;;
esac

}


