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

if [ "$#" -lt 1 ]; then
  echo "Usage: $0 <user@host> [remote_base_dir]"
  exit 1
fi

TARGET="$1"
REMOTE_BASE_DIR="${2:-/var/www/abelbirdnest-web/AbelBirdNest-Stock}"
ARTIFACT_NAME="${ARTIFACT_NAME:-$(ls -t abelbirdnest-release-*.tar.gz 2>/dev/null | head -n 1)}"
RELEASE_NAME="${RELEASE_NAME:-$(date +%Y%m%d-%H%M%S)}"
REMOTE_RELEASE_DIR="$REMOTE_BASE_DIR/releases/$RELEASE_NAME"

if [ -z "$ARTIFACT_NAME" ]; then
  echo "No artifact found. Run ./deploy/scripts/build-linux-release.sh first." >&2
  exit 1
fi

if [ ! -f "$ARTIFACT_NAME" ]; then
  echo "Artifact not found: $ARTIFACT_NAME" >&2
  echo "Run ./deploy/scripts/build-linux-release.sh first." >&2
  exit 1
fi

scp "$ARTIFACT_NAME" "$TARGET:$REMOTE_BASE_DIR/"

ssh "$TARGET" "mkdir -p '$REMOTE_RELEASE_DIR' && tar -xzf '$REMOTE_BASE_DIR/$ARTIFACT_NAME' -C '$REMOTE_RELEASE_DIR' && ln -sfn '$REMOTE_RELEASE_DIR' '$REMOTE_BASE_DIR/current'"

echo "Uploaded to $TARGET:$REMOTE_RELEASE_DIR"
