#!/bin/sh
# howcars-linux-setup - single-file Linux setup for
# "How Cars Are Made & Repaired" (Education Series).
#
# Download-at-install (house rule: one setup file; downloads are made
# over HTTPS and every file is verified against a pinned SHA-256
# checksum before it is used; a failed check installs nothing and
# leaves the machine clean). The course then runs locally on this
# computer; nothing is uploaded anywhere.
#
#   sh howcars-linux-setup              install and open the course
#   sh howcars-linux-setup --selftest   show the pinned checksums
# Environment:
#   HOWCARS_BASE_URL   override the download folder (testing)
#   HOWCARS_NO_LAUNCH  set to 1 to install without opening the course
set -eu

BASE="${HOWCARS_BASE_URL:-https://howcars.48hourrfprescue.com/files}"
APPDIR="$HOME/.local/share/howcars"
STAGE="$HOME/.local/share/.howcars-stage"
BINDIR="$HOME/.local/bin"
APP_BIN="$BINDIR/howcars"

PARTS="howcars-payload-1.zip c579e7686531ab50aa46d3292e690989f99ca110d35443716e8bad0f05a4f2ab
howcars-payload-2.zip 32c661cb96bc782c882f6a1104fbf31d42c11bc4875b88544674462a33148d15"

say() { printf '%s\n' "$*"; }

if [ "${1:-}" = "--selftest" ]; then
    say "How Cars Are Made & Repaired - Linux setup self-test"
    say "Download folder: $BASE"
    printf '%s\n' "$PARTS" | while read -r name hash; do
        [ -n "$name" ] && say "Pinned part: $name  sha256=$hash"
    done
    command -v python3 >/dev/null 2>&1 && say "python3: found" || say "python3: MISSING"
    command -v sha256sum >/dev/null 2>&1 && say "sha256sum: found" || say "sha256sum: MISSING"
    say "SELFTEST OK"
    exit 0
fi

fetch() { # url dest
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$1" -o "$2"
    elif command -v wget >/dev/null 2>&1; then
        wget -q "$1" -O "$2"
    else
        say "Neither curl nor wget was found. Install one of them and run this setup again."
        exit 1
    fi
}

extract() { # zip dest
    if command -v python3 >/dev/null 2>&1; then
        python3 -m zipfile -e "$1" "$2"
    elif command -v unzip >/dev/null 2>&1; then
        unzip -q -o "$1" -d "$2"
    else
        say "Neither python3 nor unzip was found to open the course files."
        exit 1
    fi
}

command -v python3 >/dev/null 2>&1 || { say "python3 is needed to run the course and was not found."; exit 1; }
command -v sha256sum >/dev/null 2>&1 || { say "sha256sum is needed to verify the downloads and was not found."; exit 1; }

say "How Cars Are Made & Repaired - setup"
say "Installing into $APPDIR"
rm -rf "$STAGE"
mkdir -p "$STAGE"

printf '%s\n' "$PARTS" | while read -r name hash; do
    [ -n "$name" ] || continue
    say "Downloading $name ..."
    fetch "$BASE/$name" "$STAGE/$name"
    got=$(sha256sum "$STAGE/$name" | awk '{print $1}')
    if [ "$got" != "$hash" ]; then
        say "CHECK FAILED for $name"
        say "  expected sha256 $hash"
        say "  downloaded      $got"
        say "Nothing was installed. The downloaded file was left in $STAGE for inspection."
        exit 1
    fi
    say "Checksum verified for $name."
    extract "$STAGE/$name" "$STAGE/app"
    rm -f "$STAGE/$name"
done

# Keep any existing progress across a reinstall.
if [ -d "$APPDIR/data" ]; then
    mkdir -p "$STAGE/app/data"
    cp -a "$APPDIR/data/." "$STAGE/app/data/" || true
fi
rm -rf "$APPDIR.old"
if [ -d "$APPDIR" ]; then mv "$APPDIR" "$APPDIR.old"; fi
mv "$STAGE/app" "$APPDIR"
rm -rf "$STAGE" "$APPDIR.old"

# Launcher command + desktop icon.
mkdir -p "$BINDIR"
cat > "$APPDIR/run.sh" <<'RUNEOF'
#!/bin/sh
cd "$(dirname "$0")"
if ! python3 -c "import urllib.request;urllib.request.urlopen('http://127.0.0.1:8793/api/health',timeout=1)" 2>/dev/null; then
    nohup python3 server.py >/dev/null 2>&1 &
    sleep 2
fi
if command -v xdg-open >/dev/null 2>&1; then
    xdg-open http://127.0.0.1:8793/ >/dev/null 2>&1 || true
else
    echo "Open http://127.0.0.1:8793/ in your browser."
fi
RUNEOF
chmod +x "$APPDIR/run.sh"
cat > "$APP_BIN" <<EOF
#!/bin/sh
exec "$APPDIR/run.sh"
EOF
chmod +x "$APP_BIN"

DESKTOP_DIR="$HOME/.local/share/applications"
mkdir -p "$DESKTOP_DIR"
cat > "$DESKTOP_DIR/howcars.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=How Cars
Comment=How Cars Are Made & Repaired - Education Series
Exec=$APPDIR/run.sh
Terminal=false
Categories=Education;
EOF
if [ -d "$HOME/Desktop" ]; then
    cp "$DESKTOP_DIR/howcars.desktop" "$HOME/Desktop/How Cars.desktop" || true
    chmod +x "$HOME/Desktop/How Cars.desktop" || true
fi

say "Install complete."
if [ "${HOWCARS_NO_LAUNCH:-0}" != "1" ]; then
    say "Opening the course..."
    "$APPDIR/run.sh" || true
else
    say "Start it any time with: howcars   (or the How Cars desktop icon)"
fi
