#!/bin/sh

# Copyright © Speedscale, Inc <hello@speedscale.com>

set -eu

INSTALLROOT=${INSTALLROOT:-"${HOME}/.speedscale"}
dstfile="${INSTALLROOT}/speedctl"

happy_exit() {
  # if the config already exists we don't need to init
  if [ -f "${INSTALLROOT}/config.yaml" ];then
    exit 0
  fi

  # if required variables are unset and the shell is not interactive
  # assume init will be called later.
  if [ -z "${SPEEDSCALE_API_KEY:-}" ] && [ -z "${SPEEDSCALE_EMAIL:-}" ]; then
    case "$-" in
      *i*) ;;
      *) exit 0;;
    esac
  fi

  echo
    "$dstfile" init \
      --home "${INSTALLROOT}" \
      --app-url "${SPEEDSCALE_APP_URL:-app.speedscale.com}" \
      ${SPEEDSCALE_API_KEY:+--api-key $SPEEDSCALE_API_KEY} \
      ${SPEEDSCALE_EMAIL:+--email $SPEEDSCALE_EMAIL}
  exit 0
}

validate_checksum() {
  filename=$1
  SHA=$(curl -sfL "${url}.sha256")
  echo "* Comparing checksum..."

  case $checksumbin in
    *openssl)
      checksum=$($checksumbin dgst -sha256 "${filename}" | awk '{print $NF}')
      ;;
    *shasum)
      checksum=$($checksumbin -a256 "${filename}" | awk '{print $1}')
      ;;
  esac

  if [ "$checksum" != "$SHA" ]; then
    echo "* The checksum was different." >&2
    return 1
  fi
  echo "* The checksum was the same."
  return 0
}

srcfile=''

OS=${OS:-$(uname -s)}
ARCH=${ARCH:-$(uname -m)}

case $OS in
  CYGWIN* | MINGW64* | MSYS*)
    echo "There is no speedctl support for Windows without WSL.  See https://learn.microsoft.com/en-us/windows/wsl/."
    exit 1
    ;;
  Darwin)
    srcfile=speedctl-darwin
    ;;
  Linux)
    srcfile=speedctl-linux
    ;;
  *)
    echo "There is no speedctl support for ${OS}. Please open an issue with your platform details."
    exit 1
    ;;
esac

case $ARCH in
  x86_64)
    ARCH=amd64
    ;;
  arm | arm64 | aarch64)
    ARCH=arm64
    ;;
  *)
    echo "There is no speedctl support for ${OS}/${ARCH}. Please open an issue with your platform details."
    exit 1
    ;;
esac
if [ ${srcfile} != "speedscale.exe" ]; then
  srcfile=${srcfile}-${ARCH}
fi

checksumbin=$(command -v openssl) || checksumbin=$(command -v shasum) || {
  echo "Failed to find checksum binary. Please install openssl or shasum."
  exit 1
}

tmpdir=$(mktemp -d /tmp/speedscale.XXXXXX)
url="https://downloads.speedscale.com/speedctl/${srcfile}"
install_version=${1-}

if [ "${install_version}" != "" ]; then
  echo "Installing speedctl version ${install_version}"
  url="https://downloads.speedscale.com/speedctl/${install_version}/${srcfile}"
fi

if [ -e "${dstfile}" ]; then
  echo "Checking if you are running ${install_version:-the latest speedctl}."
  if validate_checksum "${dstfile}" && [ -e "${INSTALLROOT}/config.yaml" ]; then
    echo "Your speedctl is already the current version 🎉"
    echo "To force re-downloading, delete '${dstfile}' then run again."

    "${dstfile}" version --client

    if ! which speedctl; then
      echo
      echo "speedctl is not found in your \$PATH"
      echo "add $(dirname "$dstfile") to your \$PATH to make speedctl accessible"
      echo
    fi

    exit 0
  fi
fi

# backwards compatibility: check if the arch specific variant is available
code=$(curl -I -w '%{response_code}' -s -o /dev/null "${url}-${ARCH}")
if [ "${code}" = "200" ]; then
  url=${url}-${ARCH}
  srcfile=${srcfile}-${ARCH}
fi

(
  cd "$tmpdir"

  echo "Downloading ${srcfile}..."
  curl -fLO "${url}"
  echo "Download complete!"

  if ! validate_checksum "${srcfile}"; then
    exit 1
  fi
)

(
  mkdir -p "${INSTALLROOT}"
  mv "${tmpdir}/${srcfile}" "${dstfile}"
  chmod +x "${dstfile}"
)


rm -r "$tmpdir"

echo "🎉 speedctl was successfully installed to ${dstfile}"
happy_exit
