#!/usr/bin/env sh

set -e

# Compare the SHA-256 of the downloaded tarball to the first field of
# the checksum file. Isolated so `set -e` still allows a false result
# when invoked from `if ! check_sha`.
check_sha() {
  expected=$(awk '{print $1}' "$tmpdir/$1")
  actual=$(shasum -a 256 "$tmpdir/dist/$tar" | awk '{print $1}')
  [ -n "$expected" ] && [ "$expected" = "$actual" ]
}

os=$(uname | tr '[:upper:]' '[:lower:]')
arch=$(uname -m | tr '[:upper:]' '[:lower:]' | sed -e s/x86_64/amd64/)
name=scopearctl
version=latest
channel=on-prem
domain=release.scopear.com
contact=devops@scopear.com
nodocs=0
nochecksum=0
nodownload=0
docsdir=$(pwd)/$name
tmpdir=/tmp/$name
installdir=/usr/local/bin
cmd_exists() {
  command -v "$@" >/dev/null 2>&1
}

#####################
## Parse flags
#####################

while [ $# -gt 0 ]; do
  case "$1" in
  --os=*)
    os="${1#*=}"
    ;;
  --version=*)
    version="${1#*=}"
    ;;
  --channel=*)
    channel="${1#*=}"
    ;;
  --docsdir=*)
    docsdir="${1#*=}"
    ;;
  --tmpdir=*)
    tmpdir="${1#*=}"
    ;;
  --installdir=*)
    installdir="${1#*=}"
    ;;
  --nodocs)
    nodocs=1
    ;;
  --nodownload)
    nodownload=1
    ;;
  *)
    printf "***************************\n"
    printf "* Error: Invalid argument *\n"
    printf "***************************\n"
    exit 1
    ;;
  esac
  shift
done

#####################
## Validate
#####################

if [ $os != "linux" ] && [ $os != "darwin" ]; then
  printf '\033[31m> We currently only work on linux and mac/darwin OS'
  exit 1
fi

#####################
## Use `root`
#####################

sh_c='sh -c'
if [ ! -w "$installdir" ]; then
  # use sudo if $USER doesn't have write access to the path
  if [ "$USER" != 'root' ]; then
    if cmd_exists sudo; then
      sh_c='sudo -E sh -c'
    elif cmd_exists su; then
      sh_c='su -c'
    else
      printf '\033[31m> This script requires to run commands as sudo. We are unable to find either "sudo" or "su".'
      exit 1
    fi
  fi
fi

#####################
## Download
#####################
printf '> Using Release Channel: %s\n' $channel
printf '> Using Version: %s\n' $version
url="https://$domain/downloads/$name/$channel/$version"
tar="$name-$version.tar.gz"
if [ "$arch" = "aarch64" ]; then
  arch="arm64"
fi
$sh_c "mkdir -p $tmpdir/dist"
if [ "$nodownload" -eq 0 ]; then
  code=$(curl -o /dev/null --silent --head --write-out '%{http_code}' "$url/bin/$os/$arch/$name")
  if [ "$code" != 200 ]; then
    printf '\033[31m> The OS (%s) is not supported by this installation script.\n\033[0m' $os
    exit 1
  else
    printf "> Downloading %s\n" $tar
    curl -sSL "$url/dist/$tar" -o "$tmpdir/dist/$tar"
  fi
fi

#####################
## Checksum
#####################
if [ "$nodownload" -eq 0 ]; then
  code=$(curl -o /dev/null --silent --head --write-out "%{http_code}" "$url/dist/$tar.sha256")
  if [ "$code" != "200" ]; then
    printf "> Skipping checksum validation as the sha for the release could not be found, no action needed.\n"
  else
    if [ -x "$(command -v shasum)" ]; then
      printf "> Validating checksum for %s\n" $tar
      curl -sSL "$url/dist/$tar.sha256" -o "$tmpdir/$tar.sha256"

      if ! check_sha "$tar.sha256"; then
        expected=$(awk '{print $1}' "$tmpdir/$tar.sha256")
        actual=$(shasum -a 256 "$tmpdir/dist/$tar" | awk '{print $1}')
        printf '\033[31m> Checksum failed for %s. This could be a security issue.\n' "$tar"
        printf '> Expected: %s\n' "$expected"
        printf '> Actual:   %s\n\033[0m' "$actual"
        if [ -t 0 ]; then
          read -r -p "> Would you like to continue? (y/n) " answer
          if [ "$answer" != "y" ]; then
            printf "\033[31m> Exiting, please email %s for help.\n" "$contact"
            exit 1
          fi
        else
          printf "\033[31m> Exiting, please email %s for help.\n" "$contact"
          exit 1
        fi
      fi

      rm "$tmpdir/$tar.sha256"
    else
      printf "> Skipping checksum validation as the shasum command could not be found, no action needed.\n"
    fi
  fi
fi

#####################
## Extract
#####################

printf "> Extracting to %s\n" $tmpdir
tar -xzf "$tmpdir/dist/$tar" -C $tmpdir

#####################
## Docs
#####################

if [ "$nodocs" -eq 0 ]; then
  printf "> Downloading docs to %s\n" "$docsdir/$version/"
  $sh_c "rm -rf $docsdir/$version"
  $sh_c "mkdir -p $docsdir/$version"
  $sh_c "mv $tmpdir/docs/ $docsdir/$version/"
fi

#####################
## Install
#####################

printf "> Installing %s\n" "$installdir/$name"
$sh_c "mv $tmpdir/bin/$os/$arch/$name $installdir/$name"
$sh_c "chmod +x $installdir/$name"

#####################
## Finish
#####################

printf "> Cleaning up %s\n" $tmpdir
rm -rf "$tmpdir"
printf "\033[32m> %s successfully installed!" $name
echo
$sh_c "$installdir/$name"
