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

JUMP_HOST="${JUMP_HOST:-wooo@192.168.0.110}"
TARGET_HOST="${TARGET_HOST:-ollama@192.168.0.188}"
REPO_DIR="${REPO_DIR:-/home/ollama/vibework-git}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="${REPO_ROOT:-$SCRIPT_DIR/..}"
ENV_FILE="${1:-$SCRIPT_DIR/ecosystem-hunter.env}"
SERVICE_FILE="$REPO_ROOT/scripts/systemd/agent-bounty-ecosystem-hunter.service"
LOCAL_HOME="$(cd "." && pwd)"

if [[ -z "$SERVICE_FILE" || ! -f "$SERVICE_FILE" ]]; then
  echo "service file missing: $SERVICE_FILE"
  exit 1
fi

if [[ ! -f "$ENV_FILE" ]]; then
  echo "env missing: $ENV_FILE"
  echo "Please copy from scripts/ecosystem-hunter.env.example and edit values first."
  exit 1
fi

ssh -J "$JUMP_HOST" "$TARGET_HOST" \
  "mkdir -p $REPO_DIR/scripts/systemd $REPO_DIR/scripts ~/.config/systemd/user ~/.local/logs/agent-bounty-ecosystem-hunter"

echo "[deploy] prepare local sync files..."
RSYNC_CMD=(rsync -avz -e "ssh -J $JUMP_HOST")
"${RSYNC_CMD[@]}" "$ENV_FILE" "$TARGET_HOST:$REPO_DIR/scripts/ecosystem-hunter.env"
"${RSYNC_CMD[@]}" "$LOCAL_HOME/scripts/systemd/agent-bounty-ecosystem-hunter.service" "$TARGET_HOST:$REPO_DIR/scripts/systemd/agent-bounty-ecosystem-hunter.service"
"${RSYNC_CMD[@]}" "$LOCAL_HOME/scripts/run_ecosystem_hunter.sh" "$TARGET_HOST:$REPO_DIR/scripts/run_ecosystem_hunter.sh"
"${RSYNC_CMD[@]}" "$LOCAL_HOME/scripts/nostr_agent_client.py" "$TARGET_HOST:$REPO_DIR/scripts/nostr_agent_client.py"
"${RSYNC_CMD[@]}" "$LOCAL_HOME/scripts/ecosystem-hunter-endpoints.txt" "$TARGET_HOST:$REPO_DIR/scripts/ecosystem-hunter-endpoints.txt"

ssh -J "$JUMP_HOST" "$TARGET_HOST" "\
  mkdir -p $REPO_DIR/.local/logs/agent-bounty-ecosystem-hunter && \
  chmod 600 $REPO_DIR/scripts/ecosystem-hunter.env && \
  chmod +x $REPO_DIR/scripts/run_ecosystem_hunter.sh && \
  cp $REPO_DIR/scripts/systemd/agent-bounty-ecosystem-hunter.service ~/.config/systemd/user/agent-bounty-ecosystem-hunter.service && \
  systemctl --user daemon-reload && \
  systemctl --user enable --now agent-bounty-ecosystem-hunter.service && \
  systemctl --user status --no-pager agent-bounty-ecosystem-hunter.service"
