#!/bin/bash
set -e

PROJECT="dehydrate"

# 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
    echo "Installing $PROJECT to $INSTALL_DIR"
    if [[ ! -d "$INSTALL_DIR" ]]; then
        mkdir -p "$INSTALL_DIR"
    fi
fi

# 0. see if we were passed a user to chown to
# -----------------------------------------------------------------------------
CHOWN_USER="$2"
if [[ -z "$CHOWN_USER" ]]; then
    CHOWN_USER=$USER
fi

# 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 to a temp directory
# -----------------------------------------------------------------------------
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT
URL="https://gitea.jde.nz/public/$PROJECT/releases/download/latest/$BIN"
echo "Downloading $BIN from $URL..."

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

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

# 5. Move to /usr/local/bin
# -----------------------------------------------------------------------------
docker run --rm -v "$TMPDIR:/tmp" -v "$INSTALL_DIR:/target" alpine sh -c "cp /tmp/$PROJECT /target/$PROJECT; chown $CHOWN_USER /target/$PROJECT"
rm "$TMPDIR/$PROJECT"

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