#!/usr/bin/env bash

# ------------------------------------------------------------
# Copyright 2021 The murphysec Contributors.
# Licensed under the Apache License.
# ------------------------------------------------------------

# murphysec CLI location
: ${MURPHYSEC_INSTALL_DIR:="/usr/local/bin"}

# sudo is required to copy binary to MURPHYSEC_INSTALL_DIR for linux
: ${USE_SUDO:="false"}

# Http request CLI
MURPHYSEC_HTTP_REQUEST_CLI=curl

# murphysec CLI filename
MURPHYSEC_CLI_FILENAME=murphysec

MURPHYSEC_CLI_FILE="${MURPHYSEC_INSTALL_DIR}/${MURPHYSEC_CLI_FILENAME}"

getSystemInfo() {
    ARCH=$(uname -m)
    case $ARCH in
        armv7*) ARCH="arm";;
        aarch64) ARCH="arm64";;
        x86_64) ARCH="amd64";;
    esac

    OS=$(echo `uname`|tr '[:upper:]' '[:lower:]')

    # Most linux distro needs root permission to copy the file to /usr/local/bin
    if [[ "$OS" == "linux" || "$OS" == "darwin" ]] && [ "$MURPHYSEC_INSTALL_DIR" == "/usr/local/bin" ]; then
        USE_SUDO="true"
    fi
}

verifySupported() {
    local supported=(darwin-amd64 linux-amd64 darwin-arm64)
    local current_osarch="${OS}-${ARCH}"

    for osarch in "${supported[@]}"; do
        if [ "$osarch" == "$current_osarch" ]; then
            echo "Your system is ${OS}_${ARCH}"
            return
        fi
    done

    echo "No prebuilt binary for ${current_osarch}"
    exit 1
}

runAsRoot() {
    local CMD="$*"

    if [ $EUID -ne 0 -a $USE_SUDO = "true" ]; then
        CMD="sudo $CMD"
    fi

    $CMD
}

checkHttpRequestCLI() {
    if type "curl" > /dev/null; then
        MURPHYSEC_HTTP_REQUEST_CLI=curl
    elif type "wget" > /dev/null; then
        MURPHYSEC_HTTP_REQUEST_CLI=wget
    else
        echo "Either curl or wget is required"
        exit 1
    fi
}

checkExistingMurphysec() {
    if [ -f "$MURPHYSEC_CLI_FILE" ]; then
        echo -e "\nMurphySec CLI is detected:"
        $MURPHYSEC_CLI_FILE --version
        echo -e "Reinstalling MurphySec CLI - ${MURPHYSEC_CLI_FILE}...\n"
    else
        echo -e "Installing MurphySec CLI...\n"
    fi
}


downloadFile() {

    MURPHYSEC_CLI_ARTIFACT="${MURPHYSEC_CLI_FILENAME}-${OS}-${ARCH}"


    DOWNLOAD_BASE="https://s.murphysec.com/release/"
    DOWNLOAD_URL="${DOWNLOAD_BASE}/${MURPHYSEC_CLI_ARTIFACT}"

    # Create the temp directory
    MURPHYSEC_TMP_ROOT=$(mktemp -dt murphysec-install-XXXXXX)
    ARTIFACT_TMP_FILE="$MURPHYSEC_TMP_ROOT/$MURPHYSEC_CLI_ARTIFACT"

    echo "Downloading $DOWNLOAD_URL ..."
    if [ "$MURPHYSEC_HTTP_REQUEST_CLI" == "curl" ]; then
        curl -SsL "$DOWNLOAD_URL" -o "$ARTIFACT_TMP_FILE"
    else
        wget -q -O "$ARTIFACT_TMP_FILE" "$DOWNLOAD_URL"
    fi

    if [ ! -f "$ARTIFACT_TMP_FILE" ]; then
        echo "failed to download $DOWNLOAD_URL ..."
        exit 1
    fi
}

installFile() {
    local tmp_root_murphysec_cli="$MURPHYSEC_TMP_ROOT/$MURPHYSEC_CLI_ARTIFACT"

    if [ ! -f "$tmp_root_murphysec_cli" ]; then
        echo "Failed to download MurphySec CLI."
        exit 1
    fi

    chmod 777 $tmp_root_murphysec_cli
    runAsRoot cp "$tmp_root_murphysec_cli" "$MURPHYSEC_CLI_FILE"

    if [ -f "$MURPHYSEC_CLI_FILE" ]; then
        echo "$MURPHYSEC_CLI_FILENAME installed into $MURPHYSEC_INSTALL_DIR successfully."

        $MURPHYSEC_CLI_FILE --version
    else 
        echo "Failed to install $MURPHYSEC_CLI_FILENAME"
        exit 1
    fi
}

fail_trap() {
    result=$?
    if [ "$result" != "0" ]; then
        echo "Failed to install MurphySec CLI"
        echo "For support, go to https://www.murphysec.com/docs/guides/scan-scene/cli.html"
    fi
    cleanup
    exit $result
}

cleanup() {
    if [[ -d "${MURPHYSEC_TMP_ROOT:-}" ]]; then
        rm -rf "$MURPHYSEC_TMP_ROOT"
    fi
}

installCompleted() {
    echo -e "\nTo get started with murphysec, please visit https://www.murphysec.com/docs/guides/scan-scene/cli.html"
    echo -e "\nExecute 'murphysec --help' to view all available commands."
}

# -----------------------------------------------------------------------------
# main
# -----------------------------------------------------------------------------
trap "fail_trap" EXIT

getSystemInfo
verifySupported
checkHttpRequestCLI



echo "Installing MurphySec CLI..."

downloadFile
installFile
cleanup

installCompleted