#!/bin/bash
set -e

BLUE='\033[1;94m'
GREEN='\033[1;32m'
RED='\033[1;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if curl is installed
if ! hash curl 2> /dev/null; then
  printf "${RED}error: you do not have 'curl' installed which is required for this script.${NC}\n"
  exit 1
fi

# If the install directory is not set, set it to a default
if [ -z ${APPFLOW_INSTALL_DIR+x} ]; then
  # Backwards compatibility check with warning
  if [ -z ${IONIC_CLOUD_INSTALL_DIR+x} ]; then
    APPFLOW_INSTALL_DIR=/usr/local/bin
  else
    APPFLOW_INSTALL_DIR=$IONIC_CLOUD_INSTALL_DIR
    printf "${YELLOW}warning: IONIC_CLOUD_INSTALL_DIR is deprecated. Use APPFLOW_INSTALL_DIR instead.${NC}\n\n"
  fi
fi

# If the install path is not set, set it to a default
if [ -z ${APPFLOW_INSTALL_PATH+x} ]; then
  # Backwards compatibility check with warning
  if [ -z ${IONIC_CLOUD_INSTALL_PATH+x} ]; then
    APPFLOW_INSTALL_PATH="${APPFLOW_INSTALL_DIR}/appflow"
    SHOULD_INSTALL_ALIAS=1
  else
    APPFLOW_INSTALL_PATH=$IONIC_CLOUD_INSTALL_PATH
    printf "${YELLOW}warning: IONIC_CLOUD_INSTALL_PATH is deprecated. Use APPFLOW_INSTALL_PATH instead.${NC}\n\n"
  fi
fi

# Check if the appflow cli is already installed
if [ -f "$APPFLOW_INSTALL_PATH" ]; then
  printf "${RED}error: Appflow CLI is already installed at \'${APPFLOW_INSTALL_PATH}\'${NC}\n"
  exit 1
fi

# If the desired version is not set, get the latest version from the API
if [ -z ${APPFLOW_VERSION+x} ]; then
  # Backwards compatibility check with warning
  if [ -z ${IONIC_CLOUD_VERSION+x} ]; then
    # Get the latest.json from the cdn.  This json includes a "latest_version" key with the value we're looking for
    APPFLOW_VERSION=$(curl -sL https://cdn.ionic.io/appflow-cli/releases/latest.json)
    # Use bash left strip (syntax: ${string#pattern})to find the "latest_version" key in the json and throw it away along
    # with everything before it including the leading '"' on the value of "latest_version".  This leaves us with something
    # like this: 0.2.1", <remaining json>
    APPFLOW_VERSION=${APPFLOW_VERSION#*\"latest_version\"*:*\"}
    # Use bash string replace (syntax: ${string//pattern/replacement}) to throw away the trailing '"' on the value and the
    # remaining json.
    APPFLOW_VERSION=${APPFLOW_VERSION//\"*}
    # Warn the installer that it's best practice pin to a specific version
    printf "${YELLOW}warning: We recommend specifying APPFLOW_VERSION when installing Appflow CLI as part of a pipeline. For example:${NC}\n\n"
    printf "${BLUE}(export APPFLOW_VERSION=${APPFLOW_VERSION}; curl -sL https://ionic.io/get-appflow-cli | bash)${NC}\n\n"
  else
    # Set APPFLOW_VERSION to IONIC_CLOUD_VERSION for backwards compatibility
    APPFLOW_VERSION=$IONIC_CLOUD_VERSION
    printf "${YELLOW}warning: IONIC_CLOUD_VERSION is deprecated. Use APPFLOW_VERSION instead.${NC}\n\n"
  fi
fi

# Set some constant values
APPFLOW_DOWNLOAD_URL_PREFIX="https://cdn.ionic.io/appflow-cli/releases/${APPFLOW_VERSION}/"
APPFLOW_BINARY_Darwin_arm64="appflow_Darwin_arm64"
APPFLOW_BINARY_Darwin_x86_64="appflow_Darwin_x86_64"
APPFLOW_BINARY_Linux_arm64="appflow_Linux_arm64"
APPFLOW_BINARY_Linux_i386="appflow_Linux_i386"
APPFLOW_BINARY_Linux_x86_64="appflow_Linux_x86_64"
APPFLOW_BINARY_Windows_i386="appflow_Windows_i386.exe"
APPFLOW_BINARY_Windows_x86_64="appflow_Windows_x86_64.exe"

# Lookup the platform and architecture
PLATFORM=`uname -s`
ARCH=`uname -m`

# Normalize the Windows platforms
if [[ $PLATFORM == CYGWIN* ]] || [[ $PLATFORM == MINGW* ]] || [[ $PLATFORM == MSYS* ]]; then
  PLATFORM="Windows"
fi

BINARY_LOOKUP="APPFLOW_BINARY_${PLATFORM}_${ARCH}"
DOWNLOAD_URL="${APPFLOW_DOWNLOAD_URL_PREFIX}${!BINARY_LOOKUP:-}"

# If the binary lookup wasn't successful the download url will be equal to the prefix
if [ $DOWNLOAD_URL == $APPFLOW_DOWNLOAD_URL_PREFIX ]; then
  printf "${RED}error: your platform and architecture (${PLATFORM}-${ARCH}) is unsupported.${NC}\n"
  exit 1
fi


printf "Installing Appflow CLI v${APPFLOW_VERSION}\n"

# Create a temp file for the download
TEMP_FILE=`mktemp "${TMPDIR:-/tmp}/.appflow-cli.XXXXXXXX"`

# Make sure the temp file gets cleaned up
cleanup() {
  rm -f "$TEMP_FILE"
}
trap cleanup EXIT

# Download the binary into the temp file error if the request binary wasn't found
if ! curl -sfL "$DOWNLOAD_URL" -o "$TEMP_FILE"; then
  APPFLOW_DOWNLOAD_URL_PREFIX="https://cdn.ionic.io/ionic-cloud-cli/releases/${APPFLOW_VERSION}/"
  APPFLOW_BINARY_Darwin_arm64="ionic-cloud_Darwin_arm64"
  APPFLOW_BINARY_Darwin_x86_64="ionic-cloud_Darwin_x86_64"
  APPFLOW_BINARY_Linux_arm64="ionic-cloud_Linux_arm64"
  APPFLOW_BINARY_Linux_i386="ionic-cloud_Linux_i386"
  APPFLOW_BINARY_Linux_x86_64="ionic-cloud_Linux_x86_64"
  APPFLOW_BINARY_Windows_i386="ionic-cloud_Windows_i386.exe"
  APPFLOW_BINARY_Windows_x86_64="ionic-cloud_Windows_x86_64.exe"

  BINARY_LOOKUP="APPFLOW_BINARY_${PLATFORM}_${ARCH}"
  DOWNLOAD_URL="${APPFLOW_DOWNLOAD_URL_PREFIX}${!BINARY_LOOKUP:-}"

  # Create a temp file for the download
  TEMP_FILE=`mktemp "${TMPDIR:-/tmp}/.appflow-cli.XXXXXXXX"`

  # Make sure the temp file gets cleaned up
  cleanup() {
    rm -f "$TEMP_FILE"
  }
  trap cleanup EXIT

  if ! curl -sfL "$DOWNLOAD_URL" -o "$TEMP_FILE"; then
    printf "${RED}error: Appflow CLI version ${APPFLOW_VERSION} was not found.${NC}\n"
    exit 1
  fi
fi

printf "Installation path: \'${APPFLOW_INSTALL_PATH}\'\n"
printf "  Make sure this is on your PATH.\n"

# Copy the download binary into the install path
chmod 0755 "$TEMP_FILE"
if ! mkdir -p "$APPFLOW_INSTALL_DIR" 2> /dev/null; then
  sudo -k mkdir -p "$APPFLOW_INSTALL_DIR"
fi

if ! mv "$TEMP_FILE" "$APPFLOW_INSTALL_PATH" 2> /dev/null; then
  # In the case that we are creating a ionic-cloud symlink from appflow
  # we omit the -k flag to not reset the sudo session so we can avoid 
  # requiring the user to enter their password multiple times. 
  if [ -n $SHOULD_INSTALL_ALIAS ]; then
    sudo mv "$TEMP_FILE" "$APPFLOW_INSTALL_PATH"
  else
    sudo -k mv "$TEMP_FILE" "$APPFLOW_INSTALL_PATH"
  fi
fi

if [ -n $SHOULD_INSTALL_ALIAS ]; then
  if ! ln -s "$APPFLOW_INSTALL_PATH" "${APPFLOW_INSTALL_DIR}/ionic-cloud" 2> /dev/null; then
    sudo -k ln -s "$APPFLOW_INSTALL_PATH" "${APPFLOW_INSTALL_DIR}/ionic-cloud"
  fi
fi

printf "${GREEN}Installation successful. Try 'appflow --help' to get started.${NC}\n"