#!/bin/bash

# Downloads and installs cobox
# usage: curl -o- https://cobox.cloud/releases/cobox-v1.0.0-alpha.1/download.sh | bash

BIN=$HOME/bin/cobox
APP_DIR=$HOME/.config/cobox/releases

# hard coded latest version as can't figure out how to get latest from gitlab
LATEST="1.0.0-alpha.1"

fail () {
  msg=$1
  echo "============"
  echo "Error: $msg" 1>&2
  exit 1
}

function cleanup {
  rm -rf $APP_DIR/tmp.tar.gz > /dev/null
}

install () {
  [ ! "$BASH_VERSION" ] && fail "Please use bash instead"
  GET=""
  if which curl > /dev/null; then
    GET="curl"
    GET="$GET --fail -# -L"
  elif which wget > /dev/null; then
    GET="wget"
    GET="$GET -qO-"
  else
    fail "neither wget/curl are installed"
  fi
  case `uname -s` in
    Darwin) OS="darwin";;
    Linux) OS="linux";;
    *) fail "unsupported os: $(uname -s)";;
  esac
  if uname -m | grep 64 > /dev/null; then
    ARCH="x64"
  else
    fail "only arch x64 is currently supported for single file install. please use npm instead. your arch is: $(uname -m)"
  fi
  mkdir -p $APP_DIR || fail "Could not create directory $APP_DIR, try manually downloading and extracting instead."
  cd $APP_DIR
  RELEASE="cobox-v${LATEST}-${OS}-${ARCH}"
  URL="https://cobox.cloud/releases/$RELEASE.tar.gz"
  echo "Downloading $URL"
  bash -c "$GET $URL" > $APP_DIR/tmp.tar.gz || fail "download failed"
  mkdir -p $APP_DIR/$RELEASE
  tar xzf $APP_DIR/tmp.tar.gz -C $APP_DIR/$RELEASE
  BIN="$APP_DIR/$RELEASE/cobox"
  chmod +x $BIN || fail "chmod +x failed"
  cleanup
  cat << EOF

CoBox $LATEST has been downloaded successfully. Execute it with this command:

${BIN}

Add it to your PATH with this command (add this to .bash_profile / .bashrc / .zshrc):

export PATH="\$PATH:$APP_DIR/$RELEASE"

Then simply run `cobox` to complete the install
EOF
}

install
