#!/bin/bash
# =============================================================================
# setup.sh -- One-time setup for the GitHub <-> Oracle VM command bridge
# =============================================================================
# Run this ONCE after SSHing into your Oracle VM.
# It initializes git, pulls everything from GitHub, and adds the cron job.
#
# Usage:
#   bash setup.sh
# =============================================================================

set -e
DIR="/home/opc/trading"
REMOTE_URL="https://Jake-Culberson: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@github.com/Jake-Culberson/Claud-Code.git"

echo ""
echo "============================================="
echo "  Trading Bot -- GitHub Bridge Setup"
echo "============================================="
echo ""

cd "$DIR"

# ── 1. Git init ───────────────────────────────────────────────
if [ ! -d ".git" ]; then
    echo "[1/6] Initializing git..."
    git init
    git remote add origin "$REMOTE_URL"
else
    echo "[1/6] Git already initialized — updating remote URL..."
    git remote set-url origin "$REMOTE_URL"
fi

# ── 2. Git identity ───────────────────────────────────────────
echo "[2/6] Configuring git identity..."
git config user.email "vm@oracle-trading-bot"
git config user.name "Oracle VM"

# ── 3. Pull from GitHub ───────────────────────────────────────
echo "[3/6] Pulling from GitHub..."
git pull origin main

# ── 4. Make scripts executable ───────────────────────────────
echo "[4/6] Setting permissions..."
chmod +x "$DIR/github_watcher.sh"
chmod +x "$DIR/setup.sh"

# ── 5. Install 'at' if missing (for market-hours-aware restarts)
echo "[5/6] Checking for 'at' command..."
if ! command -v at &> /dev/null; then
    sudo yum install -y at 2>/dev/null || sudo apt-get install -y at 2>/dev/null || true
    sudo systemctl enable atd 2>/dev/null && sudo systemctl start atd 2>/dev/null || true
    echo "      'at' installed"
else
    echo "      'at' already present"
fi

# ── 6. Add cron job ───────────────────────────────────────────
echo "[6/6] Adding cron job..."
CRON_LINE="*/2 * * * * /home/opc/trading/github_watcher.sh"
if crontab -l 2>/dev/null | grep -qF "github_watcher"; then
    echo "      Cron job already exists — skipping"
else
    (crontab -l 2>/dev/null; echo "$CRON_LINE") | crontab -
    echo "      Cron job added (every 2 minutes)"
fi

echo ""
echo "============================================="
echo "  Setup complete!"
echo "============================================="
echo ""
echo "The watcher checks GitHub every 2 minutes."
echo "Claude can now push commands and read results."
echo ""
echo "Watch the watcher live:"
echo "  tail -f /home/opc/trading/watcher.log"
echo ""
echo "Current cron jobs:"
crontab -l
