#!/bin/sh
OS_ARCH=$(uname -m)

PACKAGE_NAME="agent_php"

INSTALL_PATH="/opt"

BOOLEAN_TRUE="true"
BOOLEAN_FALSE="false"
MATCH_PHRASE_64BIT="64"
MATCH_PHRASE1_ARM="arm"
MATCH_PHRASE2_ARM="aarch"
QUIET="-q"
NOT_QUIET="-nq"

PRINT_OUTPUT=$NOT_QUIET

SUPPORT_MAILID=""
DOWNLOAD_DOMAIN=""
DOWNLOAD_URL=""
DOWNLOAD_PATH=""
PACKAGE_ZIP=""

LICENSE_KEY=""

IS_ARM=$BOOLEAN_FALSE
IS_NOTARM=$BOOLEAN_FALSE
IS_32BIT=$BOOLEAN_FALSE
IS_64BIT=$BOOLEAN_FALSE
IS_MUSL=$BOOLEAN_FALSE
IS_NOTMUSL=$BOOLEAN_FALSE

PrinToTerminal() {
    if [ $PRINT_OUTPUT = $NOT_QUIET ]; then
        echo "$@"
    fi
}

############### site24x7 ###############

PRODUCT_INFO="site24x7"
SUPPORT_MAILID="support@site24x7.com"
LICENSE_KEY="${S247_LICENSE_KEY}"

SetDownloadDomain() {

    case "${LICENSE_KEY}" in
    eu_*)
        DOWNLOAD_DOMAIN="https://staticdownloads.site24x7.eu"
        ;;
    cn_*)
        DOWNLOAD_DOMAIN="https://staticdownloads.site24x7.cn"
        ;;
    in_*)
        DOWNLOAD_DOMAIN="https://staticdownloads.site24x7.in"
        ;;
    au_*)
        DOWNLOAD_DOMAIN="https://staticdownloads.site24x7.net.au"
        ;;
    jp_*)
        DOWNLOAD_DOMAIN="https://staticdownloads.site24x7.jp"
        ;;
    ca_*)
		DOWNLOAD_DOMAIN="https://staticdownloads.site24x7.ca"
		;;
	uk_*)
		DOWNLOAD_DOMAIN="https://staticdownloads.site24x7.uk"
		;;
	sa_*)
		DOWNLOAD_DOMAIN="https://staticdownloads.site24x7.sa"
		;;
    aa_*)
        DOWNLOAD_DOMAIN="http://staticdownloads.localsite24x7.com"
        ;;
    ab_*)
        DOWNLOAD_DOMAIN="http://staticdownloads.localsite24x7.com"
        ;;
    *)
        DOWNLOAD_DOMAIN="https://staticdownloads.site24x7.com"
        ;;
    esac
}

SetDownloadPath() {
    #Have only true check
    if [ "$IS_NOTARM" = "$BOOLEAN_TRUE" ] && [ "$IS_32BIT" = "$BOOLEAN_TRUE" ] && [ "$IS_NOTMUSL" = "$BOOLEAN_TRUE" ]; then
        DOWNLOAD_PATH="apminsight/agents/AgentPHP/linux/glibc/386"
    elif [ "$IS_NOTARM" = "$BOOLEAN_TRUE" ] && [ "$IS_64BIT" = "$BOOLEAN_TRUE" ] && [ "$IS_NOTMUSL" = "$BOOLEAN_TRUE" ]; then
        DOWNLOAD_PATH="apminsight/agents/AgentPHP/linux/glibc/amd64"
    elif [ "$IS_ARM" = "$BOOLEAN_TRUE" ] && [ "$IS_32BIT" = "$BOOLEAN_TRUE" ] && [ "$IS_NOTMUSL" = "$BOOLEAN_TRUE" ]; then
        DOWNLOAD_PATH="apminsight/agents/AgentPHP/linux/glibc/arm"
    elif [ "$IS_ARM" = "$BOOLEAN_TRUE" ] && [ "$IS_64BIT" = "$BOOLEAN_TRUE" ] && [ "$IS_NOTMUSL" = "$BOOLEAN_TRUE" ]; then
        DOWNLOAD_PATH="apminsight/agents/AgentPHP/linux/glibc/arm64"
    elif [ "$IS_NOTARM" = "$BOOLEAN_TRUE" ] && [ "$IS_32BIT" = "$BOOLEAN_TRUE" ] && [ "$IS_MUSL" = "$BOOLEAN_TRUE" ]; then
        DOWNLOAD_PATH="apminsight/agents/AgentPHP/linux/musl/386"
    elif [ "$IS_NOTARM" = "$BOOLEAN_TRUE" ] && [ "$IS_64BIT" = "$BOOLEAN_TRUE" ] && [ "$IS_MUSL" = "$BOOLEAN_TRUE" ]; then
        DOWNLOAD_PATH="apminsight/agents/AgentPHP/linux/musl/amd64"
    else
        PrinToTerminal "Info: $OS_ARCH not supported in this version"
        ContactSupport
    fi
}

SetPackageZip() {
    PACKAGE_ZIP="${PACKAGE_NAME}.zip"
}

SetDownloadURL() {
    PrinToTerminal "Action: Setting Download url"

    SetDownloadDomain
    SetDownloadPath
    SetPackageZip

    DOWNLOAD_URL="${DOWNLOAD_DOMAIN}/${DOWNLOAD_PATH}/${PACKAGE_ZIP}"

    PrinToTerminal "Info: Download URL set as $DOWNLOAD_URL"
}

########################################

ContactSupport() {
    PrinToTerminal "Error: Installation failed, Kindly contact support $SUPPORT_MAILID"
    exit 1
}

CheckFlags() {
    for arg in "$@"; do
        if [ "$arg" = $QUIET ]; then
            PRINT_OUTPUT=$QUIET
        fi
    done
}

CheckBit() {
    PrinToTerminal "Action: Checking if ARM achitecture"

    if echo "${OS_ARCH}" | grep -i -q "${MATCH_PHRASE_64BIT}"; then
        IS_64BIT=$BOOLEAN_TRUE
        PrinToTerminal "Info: Detected as 64bit"
    else
        IS_32BIT=$BOOLEAN_TRUE
        PrinToTerminal "Info: Detected as 32bit"
    fi
}

CheckARM() {
    PrinToTerminal "Action: Checking if ARM achitecture"

    if echo "${OS_ARCH}" | grep -i -q "${MATCH_PHRASE1_ARM}"; then
        IS_ARM=$BOOLEAN_TRUE
        PrinToTerminal "Info: Detected as ARM"
    elif echo "${OS_ARCH}" | grep -i -q "${MATCH_PHRASE2_ARM}"; then
        IS_ARM=$BOOLEAN_TRUE
        PrinToTerminal "Info: Detected as ARM"
    else
        IS_NOTARM=$BOOLEAN_TRUE
        PrinToTerminal "Info: Detected as not ARM"
    fi
}

CheckStandardLibrary() {
    PrinToTerminal "Action: Checking Standard Library"

    if ldd /bin/sh | grep -q musl; then
        IS_MUSL=$BOOLEAN_TRUE
        PrinToTerminal "Info: This system is using musl as its C library"
    else
        IS_NOTMUSL=$BOOLEAN_TRUE
        PrinToTerminal "Info: This system is using glibc as its C library"
    fi
}

DownloadPackage() {
    PrinToTerminal "Action: Downloading package"
    cd "$INSTALL_PATH" || {
        PrinToTerminal "Change Directory failed, check directory name"
        exit 1
    }
    wget -O "$PACKAGE_ZIP" "$DOWNLOAD_URL"
}

RemoveDownloads() {
    PrinToTerminal "Action: Removing downloaded files"

    #condition is added for safety, to avoid unwanted removal of necesssary files
    case "${PACKAGE_ZIP}" in
    ${PACKAGE_NAME}*)
        ZIP_LOCATION="$INSTALL_PATH/$PACKAGE_ZIP"
        rm "$ZIP_LOCATION"
        ;;
    *)
        PrinToTerminal "Error: Unable to remove downloaded files"
        ;;
    esac
}

VerifyChecksum() {
    PrinToTerminal "Action: Verifying checksum"

    ZIP_LOCATION="$INSTALL_PATH/$PACKAGE_ZIP"
    ZIP_CHECKSUM=$(sha256sum "$ZIP_LOCATION" | awk '{print $1}')

    CHECKSUM_URL="${DOWNLOAD_URL}.sha256"
    LIVE_CHECKSUM="$(curl -sL $CHECKSUM_URL | awk '{print $1}')"

    PrinToTerminal "Info: Checksum of downloaded agent: $ZIP_CHECKSUM"
    PrinToTerminal "Info: Checksum of live agent: $LIVE_CHECKSUM"

    if [ "$ZIP_CHECKSUM" != "$LIVE_CHECKSUM" ]; then
        PrinToTerminal "Status: Checksum validation failed. Please retry after some time"
        RemoveDownloads
        ContactSupport
    else
        PrinToTerminal "Status: Checksum verification successful"
    fi
}

UnzipPackage() {
    PrinToTerminal "Action: Unzipping package"

    cd "$INSTALL_PATH" || {
        PrinToTerminal "Info: Change Directory failed, check directory name"
        exit 1
    }
    unzip -o "$PACKAGE_ZIP" || {
        PrinToTerminal "Info: Unzip failed"
        exit 1
    }
}

InstallPackage() {
    PrinToTerminal "Action: Installing package"
    sh "$INSTALL_PATH/zpa/bin/agent_php.sh" install "$@"
}

SetLicenseKey() {

    PrinToTerminal "Action: Checking for Licensekey"

    if [ -z "$LICENSE_KEY" ]; then

        for arg in "$@"; do
            PARAM=$arg
            VALUE="$2"

            case $PARAM in
            -lk | -license.key)
                LICENSE_KEY="$VALUE"
                ;;
            esac
            shift
        done

        if [ -n "$LICENSE_KEY" ]; then
            PrinToTerminal "Info: License key updated from CLI"
        fi
    else
        PrinToTerminal "Info: License key updated from ENV"
    fi

    if [ -z "$LICENSE_KEY" ]; then
        PrinToTerminal "Info: License key not found in ENV / CLI"
        ContactSupport
    fi
}

main() {
    CheckFlags "$@"
    SetLicenseKey "$@"
    CheckBit
    CheckARM
    CheckStandardLibrary
    SetDownloadURL
    DownloadPackage
    VerifyChecksum
    UnzipPackage
    RemoveDownloads
    InstallPackage "$@"
}

main "$@"
