#!/bin/bash
set -e

PROJECT="dehydrate"

# RUN AS ROOT
if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root" >&2
    exit 1
fi

# 0. see if we were passed a folder to install to
# -----------------------------------------------------------------------------
INSTALL_DIR="$1"
if [[ -z "$INSTALL_DIR" ]]; then
    INSTALL_DIR="/usr/local/bin"
else
    if [[ ! -d "$INSTALL_DIR" ]]; then
        mkdir -p "$INSTALL_DIR"
    fi
fi
echo "Installing $PROJECT to $INSTALL_DIR"

# 1. Determine architecture
# ----------------------------------------------------------------------------- 

ARCH=$(uname -m)
if [[ "$ARCH" == "x86_64" ]]; then
    BIN=$PROJECT.amd64
elif [[ "$ARCH" == "aarch64" || "$ARCH" == "arm64" ]]; then
    BIN=$PROJECT.arm64
else
    echo "Unsupported architecture: $ARCH" >&2
    exit 1
fi

# 3. Download the appropriate binary
# -----------------------------------------------------------------------------

URL="https://gitea.jde.nz/public/$PROJECT/releases/download/latest/$BIN"
echo "Downloading $BIN from $URL to $TMPDIR..."

curl -fsSL -o "$INSTALL_DIR/$PROJECT" "$URL"

# 4. Make it executable
# -----------------------------------------------------------------------------
chmod +x "$INSTALL_DIR/$PROJECT"

# 6. Print success message
# -----------------------------------------------------------------------------
echo "$PROJECT installed successfully to $INSTALL_DIR/$PROJECT (arch $ARCH)"
