#!/bin/sh

DEPS="tar zip"

AGON_MITE_VER="24.10.2-lts"
AGON_MITE_URL_BASE="https://www.agonmite.com/downloads"
AGON_MITE_URL="$AGON_MITE_URL_BASE/agon-mite-$AGON_MITE_VER.zip"

EMU_VER="0.9.64"
EMU_VER_B="0.9.64-2"
EMU_URL_BASE="https://github.com/tomm/fab-agon-emulator/releases/download"
EMU_URL="$EMU_URL_BASE/$EMU_VER/fab-agon-emulator-v$EMU_VER_B-linux-x86_64.tar.bz2"

ROOT="agon-mite-$AGON_MITE_VER"

check_dep() {
  if ! which $1 >/dev/null; then
    echo "\033[31mError:\033[0m Could not find $1 in your path. Install $1 and try again."
    exit 1
  fi
}

download() {
  echo -n "Downloading ${1##*/}... "
  curl -s -L $1 -o $2

  if [ $? -eq 0 ]
    then
      echo "\033[32mOK\033[0m"
    else
      echo "\033[31mERROR\033[0m"
      exit 1
  fi
}

 decompress() {
  echo -n "Decompressing Fab Agon Emulator... "
  mkdir -p "fab-agon-emulator"
  tar -xjf "fab-agon-emulator.tar.bz2" --strip-components=1 -C "fab-agon-emulator"

  if [ $? -eq 0 ]
    then
      echo "\033[32mOK\033[0m"
    else
      echo "\033[31mERROR\033[0m"
      exit 1
  fi

  echo -n "Decompressing Agon Mite... "
  mkdir -p "agon-mite"
  unzip -qq "agon-mite.zip" -d "agon-mite"

  if [ $? -eq 0 ]
    then
      echo "\033[32mOK\033[0m"
    else
      echo "\033[31mERROR\033[0m"
      exit 1
  fi
}

clear

echo "Welcome to run-agon-mite!"
echo
echo "This script allows you to easily run the Agon Mite distro for the Agon Light computer."
echo "This script automatically fetches a binary release of Fab Agon Emulator and Agon Mite."
echo "Everything is self-contained and will be stored within $(pwd)/$ROOT."
echo "No destructive action is taken by this script. If you wish to remove everything after running it do:"
echo
echo "rm -rf $(pwd)/$ROOT"
echo
echo "Nothing else is changed in your computer."
echo
echo "Credits:"
echo
echo "Fab Agon Emulator: https://github.com/tomm/fab-agon-emulator"
echo "Agon Mite: http://www.agonmite.com/"
echo
echo -n "Do you want to proceed? y/[n]: "

read answer < /dev/tty

echo

if [ "$answer" = "${answer#[yY]}" ]; then
  echo "Good bye!"
  exit 1
fi

for cmd in $DEPS; do
  check_dep $cmd
done

mkdir -p "$ROOT"
cd "$ROOT"

download "$EMU_URL" "fab-agon-emulator.tar.bz2"
download "$AGON_MITE_URL" "agon-mite.zip"

decompress

echo "Running Agon Mite in Fab Agon Emulator..."

cd "fab-agon-emulator"
"./fab-agon-emulator" --sdcard "../agon-mite"
