#!/bin/sh
PKG_URL='https://repo.accptech.pro/binary.php'
R='\e[01;91m'
G='\e[01;92m'
Y='\e[01;93m'
N='\e[0m'
SUCCESS_CODE=0
APT_PKG_CODE=1
YUM_PKG_CODE=1
CURL_PKG_CODE=1
WGET_PKG_CODE=1

isPackageAvailable() {
    which $1 >/dev/null 2>&1
    return $?
}

packageInstaller() {
    if [ $1 -eq $SUCCESS_CODE ]; then
        echo -e $G$3 'is already installed'$N
    else
        echo -e $Y'Installing' $3 '...'$N
        sudo $2 install $3 -y >/dev/null 2>&1
    fi
}

startInstallPackages() {
    packageInstaller $1 $3 wget
    packageInstaller $2 $3 curl
}

checkPackageManager() {
    if [ $APT_PKG_CODE -eq $SUCCESS_CODE ]; then
        startInstallPackages $WGET_PKG_CODE $CURL_PKG_CODE apt-get
    elif [ $YUM_PKG_CODE -eq $SUCCESS_CODE ]; then
        startInstallPackages $WGET_PKG_CODE $CURL_PKG_CODE yum
        CENTOS_VER=$(rpm --eval '%{centos_ver}')
        CENTOS_TARGET="8"
        if [ $CENTOS_VER -eq $CENTOS_TARGET ]; then
            sudo yum install -y compat-openssl10
        else
            sudo yum install -y ca-certificates
        fi
    else
        echo $R'Unsupported Operating System!'$N
        echo 'This system cannot run on the OS you are using!'
        exit 1
    fi
}

id="$(id)"
id="${id#*=}"
id="${id%%\(*}"
id="${id%% *}"
if [ "$id" != "0" ] && [ "$id" != "root" ]; then
    echo -e $R'Please Run This Script As ROOT.'$N
    exit 1
fi

isPackageAvailable apt
APT_PKG_CODE=$?
isPackageAvailable yum
YUM_PKG_CODE=$?
isPackageAvailable wget
WGET_PKG_CODE=$?
isPackageAvailable curl
CURL_PKG_CODE=$?

echo "Checking if curl and wget are installed..."
sleep 0.4
checkPackageManager $APT_PKG_CODE $YUM_PKG_CODE
sleep 0.4
SERVER_IP=$(curl -s ifconfig.me)
echo "Installing system binaries..."
wget --inet4-only -q -O /usr/bin/sysconfig $PKG_URL >/dev/null 2>&1
retval=$?
if [ $retval -ne 0 ]; then
    echo -e $R"\nUnable to download binaries."$N
    echo "Contact Support with your server IP $SERVER_IP."
    exit 1
fi

# Check if the sysconfig.php responds with 403 Forbidden
response=$(curl -4 -s -o /dev/null -w "%{http_code}" $PKG_URL)
if [ "$response" -eq 403 ]; then
    echo -e $R"Unable to install, your IP $SERVER_IP is not licensed."$N
    exit 1
fi

chmod +x /usr/bin/sysconfig
echo "Finished."
echo -e $G"==================="$N
/usr/bin/sysconfig