#!/bin/bash
set -e

# Installs bb64 on the local machine.
# 1. determines the architecture of the local machine
# 2. downloads the appropriate bb64 binary from the latest public release on Gitea (https://gitea.jde.nz/public/bb64/releases)
# 3. makes the bb64 binary executable
# 4. moves the bb64 binary to /usr/local/bin
# 5. prints a message to the user

# 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 bb64 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=$(id -u)
fi

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

ARCH=$(uname -m)
if [[ "$ARCH" == "x86_64" ]]; then
    BIN=bb64.amd64
elif [[ "$ARCH" == "aarch64" || "$ARCH" == "arm64" ]]; then
    BIN=bb64.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/bb64/releases/download/latest/$BIN"
echo "Downloading $BIN from $URL..."

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

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

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

# 6. Print success message
# -----------------------------------------------------------------------------
echo "bb64 installed successfully to $INSTALL_DIR/bb64 (arch $ARCH)"
# echo " "
# echo "Update bb64 with:"
# echo "    bb64 -u"
# echo " "
# echo "try it out with:"
# echo "    bb64 ZWNobyAiSGVsbG8td29ybGQhIGJiNjQgaXMgd29ya2luZy4i"
