#!/usr/bin/env bash
set -euo pipefail

# Build a release tarball, upload it to the Pi, and install it.
# Usage: bun run remote:deploy

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$SCRIPT_DIR/.."

source "$ROOT_DIR/scripts/config.sh"

# Build release tarball
"$ROOT_DIR/scripts/release.sh"

# Find the tarball
TARBALL=$(ls -1 "$ROOT_DIR"/dist/toes-*.tar.gz 2>/dev/null | head -1)
[ -f "$TARBALL" ] || { echo "ERROR: No tarball found in dist/"; exit 1; }
FILENAME=$(basename "$TARBALL")

echo ""
echo ">> Uploading $FILENAME to $SSH_HOST"
scp "$TARBALL" "$SSH_HOST:/tmp/$FILENAME"

echo ">> Installing on $SSH_HOST"
ssh "$SSH_HOST" bash <<SCRIPT
set -euo pipefail

DEST=~/toes
APPS_DIR=~/apps
DATA_DIR=~/data

echo ">> Extracting"
mkdir -p "\$DEST"
tar xzf "/tmp/$FILENAME" --strip-components=1 -C "\$DEST"
rm "/tmp/$FILENAME"

echo ">> Installing dependencies"
cd "\$DEST"
~/.bun/bin/bun install > /dev/null 2>&1

# Bundled apps (parallel)
REPOS_DIR="\$DATA_DIR/repos"
mkdir -p "\$REPOS_DIR" "\$APPS_DIR"

echo ">> Installing bundled apps"
pids=()
for app_dir in "\$DEST"/apps/*/; do
  app=\$(basename "\$app_dir")
  [ -f "\$app_dir/package.json" ] || continue
  (
    cp -a "\$app_dir" "\$APPS_DIR/\$app"
    ~/.bun/bin/bun install --frozen-lockfile --cwd "\$APPS_DIR/\$app" > /dev/null 2>&1 \
      || ~/.bun/bin/bun install --cwd "\$APPS_DIR/\$app" > /dev/null 2>&1
  ) &
  pids+=("\$!")
done
for pid in "\${pids[@]}"; do wait "\$pid"; done

echo ">> Installing CLI and repos"
cp -a "\$DEST"/dist/repos/*.git "\$REPOS_DIR/" 2>/dev/null || true
sudo install -m 755 "\$DEST/dist/toes" /usr/local/bin/toes

echo ">> Restarting toes"
sudo systemctl restart toes
echo ">> Done"
SCRIPT
