#!/bin/sh

echo "Acronis Plugin installation started."

REPO_BASE="https://dl.acronis.com/u/ci/cpanel"
REPO_NAME="acronis-cpanel"
CHANNEL="stable"
GPG_KEY_URL="https://dl.acronis.com/u/ci/cpanel/acronis-backup-pubkey.gpg"
GPG_KEY_URL_NEW="https://dl.acronis.com/u/ci/cpanel/acronis-backup-pubkey-new.gpg"
USER_ID=$(id -u)

if [ "${USER_ID}" != "0" ]; then
    echo "Allowed only for root user"
    exit 1
fi

usage() {
    echo "Usage: $0 [OPTIONS]" >&2
    echo "  -h                   Display this help message" >&2
    echo "  -c CHANNEL           Specify a custom release channel" >&2
}
create_repo_config() {
    if [ "${OS_NAME}" = "Ubuntu" ]; then
        echo "deb [arch=amd64 signed-by=/etc/apt/trusted.gpg.d/acronis-backup-pubkey.gpg] ${REPO_BASE}/${CHANNEL}/deb ./" |
            sudo tee /etc/apt/sources.list.d/acronis-backup-cpanel.list
    else
        if [ -f /etc/yum.repos.d/acronis-cpanel-stable.repo ]; then
            rm -rf /etc/yum.repos.d/acronis-cpanel-stable.repo
        fi
        cat >/etc/yum.repos.d/acronis-backup-cpanel.repo <<-EOF
[${REPO_NAME}-${CHANNEL}]
name=Acronis Repository for cPanel plugin - ${CHANNEL}
baseurl=${REPO_BASE}/${CHANNEL}/rpm
enabled=1
gpgcheck=1
gpgkey=${GPG_KEY_URL}
EOF
    fi
}

clean_repo_cache() {
    if [ "${OS_NAME}" = "Ubuntu" ]; then
        DEBIAN_FRONTEND=noninteractive LANG=C apt-get update
    else
        yum clean all && yum makecache
    fi
}

exitWithError() {
    echo "ERROR: $*" >&2
    exit 1
}

checkExitCode() {
    if [ $? -ne "$1" ]; then
        exitWithError "$2"
    fi
}

parse_options() {
    while getopts ':hc:' opt; do
        # shellcheck disable=SC2220
        case "$opt" in
        h)
            usage
            exit 0
            ;;
        c) CHANNEL=$OPTARG ;;
        :)
            echo "Option -$OPTARG requires an argument" >&2
            usage
            exit 3
            ;;
        esac
    done
}

detect_os() {
    echo "Detecting OS type and version ..."

    if [ -e /etc/os-release ]; then
        # shellcheck disable=SC2039
        . /etc/os-release
        DIST_ID="${ID}"
        OS_VERSION="${VERSION_ID}"
    elif [ $(which lsb_release 2>/dev/null) ]; then
        DIST_ID="$(lsb_release -s -i)"
        OS_VERSION="$(lsb_release -s -r)"
    elif [ -e /etc/redhat-release ]; then
        DIST_ID="$(cat /etc/redhat-release | sed -n -e 's/\([[:alnum:]]*\)[[:space:]].*/\1/p')"
        OS_VERSION="$(cat /etc/redhat-release | sed -n -e 's/[^0-9]*\([0-9\.]\+\).*/\1/p')"
    elif [ -e /etc/issue ]; then
        DIST_ID="$(cat /etc/issue | sed -n -e 's/\([[:alnum:]]*\)[[:space:]].*/\1/p')"
        OS_VERSION="$(cat /etc/issue | sed -n -e 's/[^0-9]*\([0-9\.]\+\).*/\1/p')"
    fi

    if [ -n "${DIST_ID}" ]; then
        DIST_ID="$(echo ${DIST_ID} | tr '[:upper:]' '[:lower:]')"
    fi

    case "$DIST_ID" in
    redhat*)
        # We use the same RPMs for RedHat as for CentOS
        OS_NAME="CentOS"
        ;;
    centos)
        OS_NAME="CentOS"
        ;;
    rhel | cloudlinux | cloudlinuxserver | almalinux | rocky)
        # We use the same RPMs for RHEL, CloudLinux, AlmaLinux and RockyLinux as for CentOS
        OS_NAME="CentOS"
        ;;
    ubuntu)
        OS_NAME="Ubuntu"
        ;;
    *)
        OS_NAME="${DIST_ID}"
        ;;
    esac
}
check_supported_os_and_version() {
    if [ -z "${OS_NAME}" ]; then
        exitWithError "Cannot determine OS name"
    fi

    if [ "${OS_NAME}" != "CentOS" ] && [ "${OS_NAME}" != "Ubuntu" ]; then
        exitWithError "Only CentOS based distribution and Ubuntu are supported at the moment"
    fi

    if [ "${OS_NAME}" = "Ubuntu" ]; then
        # In Ubuntu take two parts of OS_VERSION, e.g. for "Ubuntu 20.04.2 LTS" we consider OS_VERSION=20.04
        OS_VERSION=$(echo "$OS_VERSION" | sed -n -e 's/\([0-9]\+\.[0-9]\+\).*/\1/p')

        if [ "${OS_VERSION}" != "20.04" ] && [ "${OS_VERSION}" != "22.04" ]; then
            exitWithError "Only Ubuntu 20.04 and 22.04 are supported at the moment"
        fi
    else
        # In CentOS based OS take only first part of OS_VERSION, e.g. for CloudLinux 7.7 we consider OS_VERSION=7
        OS_VERSION=$(echo "$OS_VERSION" | sed -n -e 's/\([0-9]\+\).*/\1/p')

        if [ "${OS_VERSION}" -lt 6 ] || [ "${OS_VERSION}" -gt 10 ]; then
            exitWithError "Only CentOS/CloudLinux/Rocky/AlmaLinux 6, 7, 8, 9 and 10 are supported at the moment"
        fi
    fi
}

import_gpg_keys() {
    if [ "${OS_NAME}" = "Ubuntu" ]; then
        echo "Installing GPG ..."
        REPO_PUBKEY=$(wget -qO - "$GPG_KEY_URL_NEW" || curl -L "$GPG_KEY_URL_NEW")
        echo "$REPO_PUBKEY" | sudo tee /usr/share/keyrings/acronis-backup-pubkey.gpg > /dev/null
        echo "$REPO_PUBKEY" | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/acronis-backup-pubkey.gpg > /dev/null
        checkExitCode 0 "Unable to import Acronis Backup for cPanel gpg key."
    else
        echo "Installing GPG ..."
        yum -y install gnupg
        checkExitCode 0 "Failed to install gnupg package, see installation log above"

        rpm --import "$GPG_KEY_URL"
        checkExitCode 0 "Unable to import Acronis Backup for cPanel gpg key."
    fi
}

install_acronis_backup_cpanel() {
    # The option for Dpkg is required in case when some configs are left on the server
    # from previous versions of package.
    # Installation of Acronis Backup package always should overwrite configs,
    # this allow to deliver fixes for these files without manual actions from server' admins.

    echo "Installing Acronis Backup ..."

    if [ "${OS_NAME}" = "Ubuntu" ]; then
        apt-get install -o Dpkg::Options::="--force-confnew" -y acronis-backup-cpanel
    else
        yum install -y acronis-backup-cpanel
    fi

    checkExitCode 0 "Failed to install acronis-backup-cpanel, see installation log above"
}

parse_options "$@"
detect_os
check_supported_os_and_version
create_repo_config
import_gpg_keys
clean_repo_cache
install_acronis_backup_cpanel
