#!/bin/bash
# SPDX-License-Identifier: AGPL-3.0-or-later
# SPDX-FileCopyrightText: 2021 grommunio GmbH
# SPDX-FileCopyrightText: 2023-2025 eryx12o45, crpb

setup_repo() {
    local uri kr count krtemp

    # Check if ther eare already grommunio apt repos defined
    RELEASE_CODENAME=$(lsb_release -sc)
    SOURCES_FOUND=0
    PATTERN='^[^#]+download\.grommunio\.com'
    [ -e /etc/apt/sources.list ] && grep -qP "$PATTERN" /etc/apt/sources.list && SOURCES_FOUND=1
    grep -qPr "$PATTERN" /etc/apt/sources.list.d && SOURCES_FOUND=1
    if [ $SOURCES_FOUND -gt 0 ]; then
        return 2
    fi

    . /etc/os-release
    mirror=https://download.grommunio.com
    uri="$mirror"/RPM-GPG-KEY-grommunio
    echo
    echo -e " \x1b[36m▼\x1b[0m grommunio-setup is updating the system"
    echo
    mkdir -p /etc/apt/keyrings
    kr=/etc/apt/keyrings/download.grommunio.com.gpg
    krtemp=$(mktemp)
    while true; do
        if [ ! -f $kr ]; then
            curl -f -S -g -L -s -o "$krtemp" "$uri"
            if gpg --fingerprint --import-options show-only --import "$krtemp"
            then
                if ! gpg --batch --yes --output "$kr" --dearmor "$krtemp";
                then
                    return 1
                fi
            fi
        fi
        if [ -f $kr ]; then
            if gpg --with-colons --show-keys "$kr" |grep -q grommunio; then
                break
            else
                rm -vf "$kr"
                continue
                count=$((count+1))
            fi
        fi
        if [ $count -gt 3 ]; then
            echo -e "\x1b[36m▼\x1b[0m grommunio-setup is ending. Keyring couldn't be installed!"
            exit 1
        fi
    done
    chown -Rfv root:root /etc/apt/keyrings
    chmod -Rfv u=rwX,g=rX,o=rX /etc/apt/keyrings
    rm -f "$krtemp"

    # Don't override as we might have auth-data already set.
    # Switch to oneline to be compliant with grommunio-admin-configs..
    CREDENTIALS=username:password  # template
    # Do we already have credentials present in the system?
    CREDENTIALS_FILE=/etc/grommunio-admin-common/license/credentials.txt
    APTAUTHCONF=/etc/apt/auth.conf.d/grommunio-supported.conf
    if [ -f "$CREDENTIALS_FILE" ] && [ ! -f "$APTAUTHCONF" ]; then
        CREDENTIALS=$(cat "$CREDENTIALS_FILE")
        cat << AUTHCONF > "$APTAUTHCONF"
machine download.grommunio.com login ${CREDENTIALS%:*} password ${CREDENTIALS#*:}
AUTHCONF
    fi
    # This will work if we have valid credentials set above
    testfile=$(mktemp)
    if /usr/lib/apt/apt-helper download-file "$mirror"/supported/ "$testfile" >/dev/null 2>&1; then
        ENABLE_SUPPORTED=yes
        ENABLE_COMMUNITY=no
    else
        ENABLE_SUPPORTED=no
        ENABLE_COMMUNITY=yes
    fi
    chmod -fv u=rw,g=r,o-rwx /etc/apt/auth.conf.d/grommunio-supported.conf

    # Don't override as we might have different sources set
    cat << SOURCES > /etc/apt/sources.list.d/grommunio.sources
# A pinning example can be found in /etc/apt/preferences.d/grommunio
Types: deb
URIs: https://download.grommunio.com/community/Debian_$VERSION_ID
Suites: Debian_$VERSION_ID
Components: main
Signed-By: $kr
Enabled: $ENABLE_COMMUNITY

Types: deb
URIs: https://download.grommunio.com/devel/Debian_$VERSION_ID
Suites: Debian_$VERSION_ID
Components: main
Signed-By: $kr
Enabled: no

Types: deb
URIs: https://download.grommunio.com/supported/Debian_$VERSION_ID
Suites: Debian_$VERSION_ID
Components: main
Signed-By: $kr
Enabled: $ENABLE_SUPPORTED
SOURCES

if [ ! -f /etc/apt/preferences.d/grommunio ]; then
    cat << PINNING > /etc/apt/preferences.d/grommunio
## This is an exmaple if you need to mix in community or devel to supported
## So you won't accidentaly install all packages from community by mistake
# Package: *
# Pin: release o=grommunio, v=devel
# Pin-Priority: 50
# 
# Package: *
# Pin: release o=grommunio, v=community
# Pin-Priority: 50
# 
# Package: grommunio-admin-api
# Pin: release o=grommunio, v=community
# Pin-Priority: 500
# 
# Package: *
# Pin: release o=grommunio, v=supported
# Pin-Priority: 500
PINNING
fi
echo
echo -e " \x1b[36m▼\x1b[0m operation completed"
echo
# keep visual output on the screen for a glimpse so admin can decide
# if the logfile needs to be inspected.
sleep 1
return 0
}

repos_usage () {
        echo "$USAGE"  1>&2
        exit 2
}

repos_usage_full () {
        echo "$USAGE"  1>&2
        echo "" 1>&2
        echo "    -f        force overwrite" 1>&2
        echo "    -h        This help" 1>&2
        exit 2
}

repos_main () {
	PROGNAME=`basename "$0"`
	USAGE="Usage: $PROGNAME [-h]"

	# Process command line arguments
	OPTIND=1
	while getopts h F; do
		case $F in
		h)
			repos_usage_full
			;;
		\?)
			repos_usage
			;;
		esac
	done
	shift $(( OPTIND - 1 ))
	if [ $# != 0 ]; then
		repos_usage
	fi

	# bail out if we are not root
	if [ "`id -un`" != "root" ] ; then
		echo 1>&2
		echo "  `basename $0`: you must be 'root' to run this command." 1>&2
		echo 1>&2
		exit 1
	fi

	setup_repo
	RETVAL=$?
	if [ $RETVAL -ne 0 ]; then
		echo "${PROGNAME}: grommunio apt repository definitions already exist"
		exit $RETVAL
	fi

	exit 0
}

# Execute if stand alone
case "$0" in
	*grommunio-setup-repos)
		repos_main "$@"
		;;
esac
