#!/usr/bin/env bash

CLN_REGISTER_SERVER="https://cln.cloudlinux.com/cln/api/els/server/register"
CLN_UNREGISTER_SERVER="https://cln.cloudlinux.com/cln/api/els/server/unregister"
LICENSE=""
HOSTNAME=`hostname`

show_usage() {
    echo 'Usage: install-centos8stream-els-repo.sh [OPTION]...'
    echo ''
    echo '  -l, --license-key   User license key'
    echo '  -f, --force         Force re-register if ELS is already installed'
    echo '  -d, --delete        Delete ELS from server. Please use TuxCare portal or contact sales@tuxcare.com to cancel a license'
    echo '  -h, --help          Show this message and exit'
}

els_installed() {
    if [[ -f /etc/yum/vars/elstoken || -f /etc/yum.repos.d/centos8stream-els.repo ]]; then
        return 0
    else
        return 1
    fi
}

if [[ $# -eq 0 ]]; then
    echo "An option should be specified. See usage -h, --help."
    exit 1
fi


check_superuser_privileges() {
    echo "Checking for superuser privileges..."
    if [ "$(id -u)" -ne 0 ]; then
        echo "Error: This script must be run with superuser privileges"
        return 1
    fi
    echo "Superuser privileges confirmed"
    return 0
}

for opt in "$@"; do
    case ${opt} in
        -l|--license-key)
            if [[ -z "$2" || "$2" == -* ]]; then
                echo "Error: --license-key requires an argument"
                show_usage
                exit 1
            fi
            LICENSE=$2 ; shift ;;
        -f|--force)
            FORCE=true ; shift ;;
        -d|--delete)
            DELETE=true ; shift ;;
        -h|--help)
            show_usage ; exit 0 ;;
        -*|--*)
            echo; echo "Unrecognized option: ${opt}"; show_usage ; exit 1 ;;
    esac
done

if ! check_superuser_privileges; then
    exit 14
fi
if [[ ! -z $FORCE ]]; then
    rm -rf /etc/yum/vars/elstoken
    rm -rf /etc/yum.repos.d/centos8stream-els.repo
fi

if [[ ! -z $DELETE ]]; then
    CLN_UNREGISTER=""
    if els_installed; then
        CLN_UNREGISTER=$(curl -i -s -X POST "$CLN_UNREGISTER_SERVER?token=$(cat /etc/yum/vars/elstoken)")
    fi
    if [[ ! "$CLN_UNREGISTER" == *"200"* ]]; then
        if [[ -z $CLN_UNREGISTER ]]; then
            echo "DELETE: elstoken wasn't found. Server is not registered"
        else
            echo "Get incorrect status from CLN: $CLN_UNREGISTER"
        fi
        exit 1
    else
        echo "Unregister successfully"
    fi

    rm -rf /etc/yum/vars/elstoken
    rm -rf /etc/yum.repos.d/centos8stream-els.repo
    yum remove els-define -y
    echo "CentOS ELS deleted successfully"
    exit
fi

# check centos-release file
if [[ ! -f /etc/centos-release ]]; then
    echo "This server is not RHEL based"
    exit 1
fi

# check centos version
centos_release="$(cat /etc/centos-release)"
if [[ ! "${centos_release}" == *"CentOS Stream release 8"* ]]; then
    echo "This server is not CentOS Stream release 8"
    exit 1
fi

# check license key
if [[ -z $LICENSE ]]; then
    echo "License key should be specified with -l, --license-key."
    echo "See -h, --help."
    exit 1
fi

# check if els is installed
if [[ -f /etc/yum/vars/elstoken || -f /etc/yum.repos.d/centos8stream-els.repo ]]; then
    echo "This server has installed ELS repo and token"
    echo "For re-registration license run script with --force"
    exit 1
fi

# download and import GPG key
curl -sSL https://repo.tuxcare.com/tuxcare/RPM-GPG-KEY-TuxCare -o /etc/pki/rpm-gpg/RPM-GPG-KEY-TuxCare
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-TuxCare
[ $? -eq 0 ]  || exit 1

# get token
CLN_REGISTER=$(curl -i -X POST -H "Content-Type: application/json" -H "accept: */*" -d "{\"key\": \"$LICENSE\", \"host_name\": \"$HOSTNAME\"}" "$CLN_REGISTER_SERVER")
CLN_CODE=$(head -n1 <<< "$CLN_REGISTER")

if [[ ! "$CLN_CODE" == *"200"* ]]; then
    echo "Get incorrect status from CLN: $CLN_REGISTER"
    exit 1
fi

TOKEN=$(echo "$CLN_REGISTER" | grep -oP '"token":"\K[\w\d-]*')

if [[ -z $TOKEN ]]; then
    echo "Something went wrong. Token not defined"
    exit 1
fi

echo "${TOKEN}" > /etc/yum/vars/elstoken

# create yum repo config
cat <<EOT >> /etc/yum.repos.d/centos8stream-els.repo
[centos8stream-els]
name = CentOS 8 Stream Extended Lifecycle Support by CloudLinux Updates
baseurl = https://repo.tuxcare.com/centos8stream-els/\$elstoken/updates/\$basearch/
enabled = 1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-TuxCare
gpgcheck=0

[centos8stream-els-testing]
name = CentOS 8 Stream Extended Lifecycle Support by CloudLinux Updates-Testing
baseurl = https://repo.tuxcare.com/centos8stream-els/\$elstoken/updates-testing/\$basearch/
enabled = 0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-TuxCare
gpgcheck=0

[centos8stream-els-src]
name = CentOS 8 Stream Extended Lifecycle Support by CloudLinux SRPMS
baseurl = https://repo.tuxcare.com/centos8stream-els/\$elstoken/updates/Sources/
enabled = 0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-TuxCare
gpgcheck=0
EOT

yum clean all
yum install -y els-define --disablerepo=* --enablerepo=centos8stream-els

echo "CentOS ELS installed successfully"
