#!/bin/sh
# SHAKS installer for macOS and Linux.
#   curl -fsSL https://shaks.pages.dev/install.sh | sh
# Downloads the latest release from github.com/Vaishakkr/shaks-app, checks its SHA-256 against the
# published checksums, installs it and opens it. Nothing else on the computer is changed.
set -eu
REL="https://github.com/Vaishakkr/shaks-app/releases/latest/download"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
say() { printf '\033[1;34m==>\033[0m %s\n' "$1"; }
fail() { printf '\033[1;31mSHAKS could not be installed:\033[0m %s\n' "$1" >&2; exit 1; }

check() {
  file="$1"; name="$2"
  curl -fsSL "$REL/SHA256SUMS.txt" -o "$TMP/sums" || fail "could not download the checksums."
  want=$(grep " $name\$" "$TMP/sums" | awk '{print $1}')
  [ -n "$want" ] || fail "no checksum published for $name."
  if command -v shasum >/dev/null 2>&1; then got=$(shasum -a 256 "$file" | awk '{print $1}'); else got=$(sha256sum "$file" | awk '{print $1}'); fi
  [ "$want" = "$got" ] || fail "the download did not match its checksum. Please try again."
  say "Checksum verified"
}

case "$(uname -s)" in
  Darwin)
    [ "$(uname -m)" = "arm64" ] || fail "this release is for Macs with Apple silicon (M1 or later)."
    say "Downloading SHAKS for macOS"
    curl -fL --progress-bar "$REL/SHAKS-macOS.dmg" -o "$TMP/SHAKS.dmg" || fail "the download failed. Check the internet connection."
    check "$TMP/SHAKS.dmg" "SHAKS-macOS.dmg"
    say "Installing"
    MNT="$TMP/mnt"; mkdir -p "$MNT"
    hdiutil attach -nobrowse -quiet -mountpoint "$MNT" "$TMP/SHAKS.dmg" || fail "could not open the disk image."
    DEST="/Applications"
    [ -w "$DEST" ] || { DEST="$HOME/Applications"; mkdir -p "$DEST"; }
    osascript -e 'tell application "SHAKS" to quit' >/dev/null 2>&1 || true
    rm -rf "$DEST/SHAKS.app"
    cp -R "$MNT/SHAKS.app" "$DEST/" || { hdiutil detach -quiet "$MNT"; fail "could not copy SHAKS to $DEST."; }
    hdiutil detach -quiet "$MNT" || true
    xattr -dr com.apple.quarantine "$DEST/SHAKS.app" 2>/dev/null || true
    say "SHAKS is installed in $DEST. Opening it now."
    open "$DEST/SHAKS.app"
    ;;
  Linux)
    command -v apt-get >/dev/null 2>&1 || fail "this installer needs a Debian or Ubuntu based system (apt)."
    say "Downloading SHAKS for Linux"
    curl -fL --progress-bar "$REL/shaks-linux.deb" -o "$TMP/shaks.deb" || fail "the download failed. Check the internet connection."
    check "$TMP/shaks.deb" "shaks-linux.deb"
    say "Installing (your password may be asked)"
    sudo apt-get install -y "$TMP/shaks.deb" || fail "apt could not install the package."
    say "SHAKS is installed. Find it in your applications menu under Office."
    ;;
  *) fail "on Windows, use the PowerShell command on shaks.pages.dev/download.html." ;;
esac
