#!/usr/bin/env bash
# Bootstrap RenTech Today Trades on a fresh Ubuntu VPS (DigitalOcean / Hetzner).
#
# Usage (as root on the VPS, after cloning the repo):
#
#   export TODAY_TRADES_PASSWORD='pick-a-strong-password'
#   export DEPLOY_USER=root          # or ubuntu / your user
#   export REPO_DIR=/opt/rentech/trading_bot
#   bash deploy/today_trades/bootstrap_vps.sh
#
# Then put Caddy/nginx in front of 127.0.0.1:8765 for HTTPS.
set -euo pipefail

REPO_DIR="${REPO_DIR:-/opt/rentech/trading_bot}"
DEPLOY_USER="${DEPLOY_USER:-root}"
PASSWORD="${TODAY_TRADES_PASSWORD:-}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [[ -z "${PASSWORD}" ]]; then
  echo "Set TODAY_TRADES_PASSWORD before running." >&2
  exit 1
fi

if [[ ! -d "${REPO_DIR}/RenTech" ]]; then
  echo "REPO_DIR=${REPO_DIR} does not look like the trading_bot repo." >&2
  echo "Clone first, e.g.: git clone <url> ${REPO_DIR}" >&2
  exit 1
fi

export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y git python3 python3-venv python3-pip curl

cd "${REPO_DIR}"
python3 -m venv .venv
.venv/bin/pip install --upgrade pip
.venv/bin/pip install -r "${SCRIPT_DIR}/requirements.txt"

mkdir -p RenTech/data/logs RenTech/data/live_state
chown -R "${DEPLOY_USER}:${DEPLOY_USER}" "${REPO_DIR}" || true

# First snapshot so the site has data immediately
sudo -u "${DEPLOY_USER}" -H bash -lc "cd '${REPO_DIR}' && .venv/bin/python -m RenTech.monitor.refresh_today_trades"

# systemd units
UNIT_DIR=/etc/systemd/system
sed "s|ROOT_OR_DEPLOY_USER|${DEPLOY_USER}|g; s|/opt/rentech/trading_bot|${REPO_DIR}|g; s|CHANGE_ME|${PASSWORD}|g" \
  "${SCRIPT_DIR}/rentech-today-trades.service" > "${UNIT_DIR}/rentech-today-trades.service"
sed "s|ROOT_OR_DEPLOY_USER|${DEPLOY_USER}|g; s|/opt/rentech/trading_bot|${REPO_DIR}|g" \
  "${SCRIPT_DIR}/rentech-today-refresh.service" > "${UNIT_DIR}/rentech-today-refresh.service"
# Timer uses fixed OnCalendar in America/New_York — set host timezone
timedatectl set-timezone America/New_York || true
cp "${SCRIPT_DIR}/rentech-today-refresh.timer" "${UNIT_DIR}/rentech-today-refresh.timer"

systemctl daemon-reload
systemctl enable --now rentech-today-trades.service
systemctl enable --now rentech-today-refresh.timer

echo
echo "=== Done ==="
echo "Web (local):  http://127.0.0.1:8765/today_trades.html"
echo "Public IP:    http://$(curl -s ifconfig.me || echo YOUR_IP):8765/today_trades.html"
echo "  (open firewall port 8765, or put Caddy on 443 → 127.0.0.1:8765)"
echo
echo "Refresh timer:"
systemctl list-timers rentech-today-refresh.timer --no-pager || true
echo
echo "Edit held names anytime:"
echo "  nano ${REPO_DIR}/RenTech/monitor/config/today_trades_book.json"
echo "  systemctl start rentech-today-refresh.service"
echo
echo "Password is set via TODAY_TRADES_PASSWORD in the systemd unit."
