#!/bin/sh
# Xygeni Scanner Bootstrap - Download, verify and install.
# Usage: ./get-xygeni.sh [install_dir]   (default: $HOME/.xygeni)
#
# Verify this script:
#   h=$(curl -s https://raw.githubusercontent.com/xygeni/xygeni/main/checksum/latest/get-xygeni.sh.sha256)
#   echo "$h get-xygeni.sh" | sha256sum -c
set -e
# Download helper: uses curl if available, falls back to wget
fetch() { curl -sSfL "$1" 2>/dev/null || wget -qO- "$1"; }
DIR="${1:-$HOME/.xygeni}"
# Check and exit if already installed
[ -x "$DIR/xygeni" ] && { echo "Xygeni scanner already installed in $DIR" >&2; exit 0; }
ZIP="$(mktemp)"
trap 'rm -f "$ZIP"' EXIT
# Download scanner and checksum
fetch https://get.xygeni.io/latest/scanner/xygeni_scanner.zip > "$ZIP"
EXPECT=$(fetch https://raw.githubusercontent.com/xygeni/xygeni/main/checksum/latest/xygeni-release.zip.sha256)
ACTUAL=$(sha256sum "$ZIP" 2>/dev/null || shasum -a 256 "$ZIP")
ACTUAL=$(echo "$ACTUAL" | awk '{print $1}')
# Verify checksum
[ "$EXPECT" = "$ACTUAL" ] || { echo "Checksum mismatch: expected $EXPECT, got $ACTUAL" >&2; exit 1; }
# Extract scanner: uses unzip if available, falls back to jar (Java is required for the scanner)
mkdir -p "$DIR"
unzip -qo "$ZIP" -d "$DIR" 2>/dev/null || (cd "$DIR" && jar xf "$ZIP")
mv "$DIR/xygeni_scanner"/* "$DIR/" && rmdir "$DIR/xygeni_scanner"  # flatten nested dir
echo "Xygeni scanner installed in $DIR"
