#!/usr/bin/env bash

if [[ ! ${EUID} -eq 0 ]]; then
  echo "You must run the installer as a superuser"
  exit 1
fi

VERSION=$1
if [[ -z ${VERSION} ]]; then
    VERSION="latest"
fi

API_KEY=$2

# where a previous installation stores its config (keep in sync with
# config('app.user_config_file') / SMTP2GO_USER_CONFIG_FILE)
CONFIG_FILE="${SMTP2GO_USER_CONFIG_FILE:-/var/lib/SMTP2GO/config.json}"

# alpha builds talk to the staging service; everything else uses production.
if [[ ${VERSION} == "alpha" ]]; then
    SERVICE_URL="https://cpanel-server.2050.nz"
else
    SERVICE_URL="https://cpanelservice2.smtp2go.com"
fi

# If the key wasn't supplied as an argument, reuse the key from a previous
# installation when we can, otherwise prompt for it. Read from the controlling
# terminal directly so this still works under the advertised
# `curl -o installer ... && bash installer latest` flow.
if [[ -z ${API_KEY} ]]; then
    # pull any existing key out of the config file left by a prior install
    EXISTING_API_KEY=""
    if [[ -r ${CONFIG_FILE} ]]; then
        EXISTING_API_KEY=$(grep -o '"smtp2go_api_key":"[^"]*"' "${CONFIG_FILE}" | head -n1 | cut -d'"' -f4)
    fi

    # let the user know which permissions the key needs before they create/paste one
    if [[ -r /dev/tty || -z ${EXISTING_API_KEY} ]]; then
        cat <<'EOF'
The SMTP2GO API key must be granted the following permissions:
  - /users/smtp/add
  - /users/smtp/remove
  - /users/smtp/view
  - /domain/add
  - /domain/remove
  - /domain/verify
  - /domain/view
EOF
    fi

    if [[ -r /dev/tty ]]; then
        if [[ -n ${EXISTING_API_KEY} ]]; then
            read -r -p "Found an existing SMTP2GO API key. Press Enter to reuse it, or paste a new key: " API_KEY < /dev/tty
        else
            read -r -p "Enter your SMTP2GO API key: " API_KEY < /dev/tty
        fi
    elif [[ -z ${EXISTING_API_KEY} ]]; then
        read -r -p "Enter your SMTP2GO API key: " API_KEY
    fi

    # nothing entered -> fall back to the stored key from the previous install
    if [[ -z ${API_KEY} && -n ${EXISTING_API_KEY} ]]; then
        API_KEY="${EXISTING_API_KEY}"
        echo "Reusing your existing SMTP2GO API key."
    fi
fi

if [[ -z ${API_KEY} ]]; then
    echo "An SMTP2GO API key is required to download the plugin. Aborting."
    exit 1
fi

runFatal() {
    ${RUN_FATAL} "$1" "$2"
    if [[ $? != 0 ]]; then
        exit 1
    fi
}

PLUGIN_FILE_NAME="SMTP2GO-whm-${VERSION}.tar.gz"
PLUGIN_DIR=/var/cpanel/addons
SMTP2GO_PLUGIN_DIR="${PLUGIN_DIR}/SMTP2GO"
INSTALL_DIR=/usr/local/SMTP2GO
INSTALL_FILE="${INSTALL_DIR}/bin/install.sh"
VERSION_FILE="${SMTP2GO_PLUGIN_DIR}/version.txt"

STARTING_INSTALLATION_MESSAGE="Starting SMTP2GO WHM Plugin installation..."
PLUGIN_TAR_EXISTS_MESSAGE="${PLUGIN_FILE_NAME} exists, removing it"
PLUGIN_DOWNLOAD_MESSAGE="Downloading latest plugin version."
FAILED_PLUGIN_DOWNLOAD_MESSAGE="Failed to download the SMTP2GO cPanel plugin, aborting installation"
FAILED_PLUGIN_UNPACK_MESSAGE="Failed to unpack ${PLUGIN_FILE_NAME} to ${PLUGIN_DIR}. Aborting installation."
RUNNING_INSTALL_MESSAGE="Running ${INSTALL_FILE}..."
INSTALLATION_FAILED_MESSAGE="Failed to install the SMTP2GO plugin."

echo ${STARTING_INSTALLATION_MESSAGE}

if [[ -f ${PLUGIN_FILE_NAME} ]]; then
    echo ${PLUGIN_TAR_EXISTS_MESSAGE}
    rm ${PLUGIN_FILE_NAME}
fi

# verify the API key with the SMTP2GO service and obtain a short-lived signed
# download URL for the tarball. The tarball is no longer publicly accessible.
echo "Verifying SMTP2GO API key..."
REGISTER_RESPONSE=$(curl -s -X POST "${SERVICE_URL}/installer/request" \
    --data-urlencode "api_key=${API_KEY}" \
    --data-urlencode "channel=${VERSION}")

# the service returns JSON with unescaped slashes, so the URL can be pulled out directly
DOWNLOAD_URL=$(echo "${REGISTER_RESPONSE}" | grep -o '"url":"[^"]*"' | cut -d'"' -f4)

if [[ -z ${DOWNLOAD_URL} ]]; then
    echo "Could not verify the SMTP2GO API key:"
    echo "${REGISTER_RESPONSE}"
    exit 1
fi

echo ${PLUGIN_DOWNLOAD_MESSAGE}
wget -O "${PLUGIN_FILE_NAME}" "${DOWNLOAD_URL}" &>/dev/null

if [[ $? != 0 ]]
then
    echo ${FAILED_PLUGIN_DOWNLOAD_MESSAGE}
    exit 1
fi

rm -rf ${INSTALL_DIR}
mkdir ${INSTALL_DIR}
chmod 0755 ${INSTALL_DIR}

tar -xf ${PLUGIN_FILE_NAME} -C ${INSTALL_DIR}

/usr/bin/chown -R root:root ${INSTALL_DIR}


if [[ $? != 0 ]]
then
    echo ${FAILED_PLUGIN_UNPACK_MESSAGE}
    exit 1
fi

rm ${PLUGIN_FILE_NAME}

echo ${RUNNING_INSTALL_MESSAGE}

# hand the already-verified key to the inner installer so the user isn't prompted again
export SMTP2GO_API_KEY="${API_KEY}"
${INSTALL_FILE}
if [[ $? != 0 ]]; then
    echo ${INSTALLATION_FAILED_MESSAGE}
    exit 1
fi

VERSION=$(cat ${VERSION_FILE})
INSTALL_SUCCESS_MESSAGE="Version ${VERSION} of the SMTP2GO plugin has been successfully installed."

echo
echo ${INSTALL_SUCCESS_MESSAGE}
