#!/usr/bin/env bash
#
# install.sh - download, verify and install the Flint portable executable.
# Intended for bash users on Windows (MSYS2 / Git-Bash / WSL) or anyone who
# prefers `curl | bash`. Flint itself is a Windows GUI app; after install
# launch it from Windows.
#
# Usage (bash):
#   curl -fsSL https://flintusb.pages.dev/install.sh | bash
#   # specify a destination:
#   curl -fsSL https://flintusb.pages.dev/install.sh | bash -s -- "$HOME/.local/bin"
#
# The script downloads flint.exe from the latest GitHub release asset URL,
# fetches the flint.exe.sha256 sidecar, and refuses to keep the file unless
# the SHA-256 matches.
#
# Security: piping remote scripts to a shell is risky. Only run over HTTPS
# and read the script first. The download itself is protected by a checksum:
# mismatches delete the file and abort.

set -euo pipefail

ASSET_URL="${ASSET_URL:-https://github.com/gowthvm/Flint/releases/latest/download/flint.exe}"
SHA_URL="${SHA_URL:-https://github.com/gowthvm/Flint/releases/latest/download/flint.exe.sha256}"
DEST="${1:-$HOME/.local/bin/flint.exe}"

mkdir -p "$(dirname "$DEST")"
TMP="$DEST.partial"

echo "Downloading Flint from $ASSET_URL ..."
if ! curl -fsSL -o "$TMP" "$ASSET_URL"; then
  rm -f "$TMP"
  echo "error: download failed. Is the release feed public?"
  echo "If the repository is still private, these URLs return 404."
  exit 1
fi

SIZE="$(wc -c < "$TMP")"
if [ "$SIZE" -lt 1000000 ]; then
  rm -f "$TMP"
  echo "error: downloaded file is only ~$((SIZE / 1024)) KB and looks invalid."
  echo "This usually means the release feed is unavailable (private repo)."
  exit 1
fi

echo "Fetching checksum sidecar ..."
EXPECTED="$(curl -fsSL "$SHA_URL" 2>/dev/null | tr -d '[:space:]' || true)"

if [ -n "$EXPECTED" ]; then
  ACTUAL="$(sha256sum "$TMP" | awk '{print $1}')"
  if [ "$(expr "$EXPECTED" : '^[0-9a-fA-F]\{64\}$')" -eq 0 ] || \
     [ "$(printf '%s' "$EXPECTED" | tr '[:upper:]' '[:lower:]')" != "$(printf '%s' "$ACTUAL")" ]; then
    rm -f "$TMP"
    echo "error: SHA-256 mismatch."
    echo "  expected: $EXPECTED"
    echo "  got:      $ACTUAL"
    echo "The download was deleted for safety."
    exit 1
  fi
  echo "SHA-256 verified: $ACTUAL"
else
  echo "warning: no checksum sidecar found; could not verify SHA-256."
fi

mv -f "$TMP" "$DEST"
chmod +x "$DEST" 2>/dev/null || true

echo ""
echo "Flint installed to:"
echo "  $DEST"
echo ""
echo "Run it from Windows (it is a Windows GUI app)."
echo "Tip: run as Administrator to flash/wipe/clone drives."