#!/usr/bin/env bash

ABRA_VERSION="0.2.2-alpha"
ABRA_RELEASE_URL="https://git.coopcloud.tech/api/v1/repos/coop-cloud/abra/releases/tags/$ABRA_VERSION"

function show_banner {
  echo ""
  echo "   ____                           ____ _                 _ "
  echo "  / ___|___         ___  _ __    / ___| | ___  _   _  __| |"
  echo " | |   / _ \ _____ / _ \| '_ \  | |   | |/ _ \| | | |/ _' |"
  echo " | |__| (_) |_____| (_) | |_) | | |___| | (_) | |_| | (_| |"
  echo "  \____\___/       \___/| .__/   \____|_|\___/ \__,_|\__,_|"
  echo "                        |_|"
  echo ""
  echo ""
  echo "          === Public interest infrastructure ===           "
  echo ""
  echo ""
}

function install_abra_release {
  mkdir -p "$HOME/.local/bin"

  if ! type "curl" > /dev/null 2>&1; then
    echo "'curl' is not installed, cannot proceed..."
    echo "perhaps try installing manually via the releases URL?"
    echo "https://git.coopcloud.tech/coop-cloud/abra/releases"
    exit 1
  fi

  if ! type "curl" > /dev/null 2>&1; then
    error "'python3' is not installed, cannot proceed..."
    echo "perhaps try installing manually via the releases URL?"
    echo "https://git.coopcloud.tech/coop-cloud/abra/releases"
  fi

  # FIXME: support different architectures
  PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m)
  sed_command='s/.*"assets":\[\{[^}]*"name":"abra.*_'"$PLATFORM"'"[^}]*"browser_download_url":"([^"]*)".*\].*/\1/p'
  release_url=$(curl -s $ABRA_RELEASE_URL | sed -En $sed_command)

  echo "downloading $ABRA_VERSION $PLATFORM binary release for abra..."
  curl --progress-bar "$release_url" --output "$HOME/.local/bin/abra"
  chmod +x "$HOME/.local/bin/abra"

  echo "abra installed to $HOME/.local/bin/abra"
}

function run_installation {
  show_banner
  install_abra_release
}

run_installation "$@"
exit 0
