#!/bin/sh
set -e

# Change this to your actual website domain once hosted
WEBSITE_URL="https://YOUR_WEBSITE_DOMAIN.com"
LATEST_TAG="v0.1.0"

echo "Detecting OS and Architecture..."

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"

if [ "$OS" = "linux" ]; then
    OS_NAME="linux"
elif [ "$OS" = "darwin" ]; then
    OS_NAME="macos"
else
    echo "Error: Unsupported OS ($OS). Please download manually."
    exit 1
fi

if [ "$ARCH" = "x86_64" ]; then
    ARCH_NAME="amd64"
elif [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
    ARCH_NAME="arm64"
else
    echo "Error: Unsupported architecture ($ARCH). Please download manually."
    exit 1
fi

if [ "$OS_NAME" = "linux" ] && [ "$ARCH_NAME" = "arm64" ]; then
    echo "Error: Linux arm64 binaries are not provided by default yet. Please build from source."
    exit 1
fi

ARCHIVE="psh-${OS_NAME}-${ARCH_NAME}.tar.gz"

echo "Latest release is $LATEST_TAG"

DOWNLOAD_URL="${WEBSITE_URL}/releases/${LATEST_TAG}/${ARCHIVE}"
CHECKSUMS_URL="${WEBSITE_URL}/releases/${LATEST_TAG}/checksums.txt"

TMP_DIR=$(mktemp -d -t psh-install-XXXXXX)
cd "$TMP_DIR"

echo "Downloading $ARCHIVE..."
curl -fsSL "$DOWNLOAD_URL" -o "$ARCHIVE" || { echo "Error: Download failed! Ensure the URL is correct and the server is running."; exit 1; }

echo "Downloading checksums.txt..."
curl -fsSL "$CHECKSUMS_URL" -o "checksums.txt" || { echo "Error: Failed to download checksums."; exit 1; }

echo "Verifying checksum..."
# Filter checksums just for our file
grep "$ARCHIVE" checksums.txt > checksum_single.txt

if command -v sha256sum >/dev/null 2>&1; then
    sha256sum -c checksum_single.txt || { echo "Error: Checksum validation failed!"; exit 1; }
elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 -c checksum_single.txt || { echo "Error: Checksum validation failed!"; exit 1; }
else
    echo "Warning: No sha256sum or shasum found to verify binary. Proceeding anyway."
fi

echo "Extracting binary..."
tar -xzf "$ARCHIVE"

echo "Installing to /usr/local/bin (requires sudo)..."
sudo mv psh /usr/local/bin/psh
sudo mv psh-lsp /usr/local/bin/psh-lsp 2>/dev/null || sudo ln -sf /usr/local/bin/psh /usr/local/bin/psh-lsp

cd - > /dev/null
rm -rf "$TMP_DIR"

echo ""
echo "Successfully installed P# v${LATEST_TAG#v}!"
echo "Run 'psh --help' to get started."
psh run 2>/dev/null || true
