#!/bin/bash
# Lethean Testnet — Production Deploy Script
# Transfers images and config to a remote server and starts the stack.
#
# Usage:
#   bash deploy.sh user@server
#   bash deploy.sh user@server /opt/lethean/docker
#
# Prerequisites on the remote server:
#   - Docker + Docker Compose v2
#   - SSH access

set -e

REMOTE="${1:?Usage: deploy.sh user@server [install_dir]}"
INSTALL_DIR="${2:-/opt/lethean/docker}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
IMAGES="$SCRIPT_DIR/dist/lethean-testnet-images.tar.gz"

if [ ! -f "$IMAGES" ]; then
    echo "Building image bundle..."
    mkdir -p "$SCRIPT_DIR/dist"
    docker save \
        lthn/chain:testnet \
        lthn/explorer:testnet \
        lthn/trade-api:testnet \
        lthn/trade-frontend:testnet \
        lthn/pool:testnet \
        lthn/lns:testnet \
        lthn/docs:testnet \
        | gzip > "$IMAGES"
fi

echo "Image bundle: $(du -h "$IMAGES" | cut -f1)"
echo "Deploying to $REMOTE:$INSTALL_DIR"
echo ""

# Create remote directory
ssh "$REMOTE" "mkdir -p $INSTALL_DIR"

# Transfer files
echo "Transferring config files..."
scp "$SCRIPT_DIR/docker-compose.pull.yml" "$REMOTE:$INSTALL_DIR/"
scp "$SCRIPT_DIR/.env.example" "$REMOTE:$INSTALL_DIR/"
scp "$SCRIPT_DIR/pool-config.json" "$REMOTE:$INSTALL_DIR/"
scp "$SCRIPT_DIR/health.sh" "$REMOTE:$INSTALL_DIR/"
scp "$SCRIPT_DIR/lethean-testnet.service" "$REMOTE:$INSTALL_DIR/"
scp "$SCRIPT_DIR/docker-compose.node.yml" "$REMOTE:$INSTALL_DIR/"
scp "$SCRIPT_DIR/docker-compose.exit.yml" "$REMOTE:$INSTALL_DIR/"
scp -r "$SCRIPT_DIR/demos/helpers" "$REMOTE:$INSTALL_DIR/demos/"

# Create .env if it doesn't exist — generate unique JWT secret
ssh "$REMOTE" "
  if [ ! -f $INSTALL_DIR/.env ]; then
    cp $INSTALL_DIR/.env.example $INSTALL_DIR/.env
    JWT=\$(openssl rand -hex 32 2>/dev/null || head -c 64 /dev/urandom | xxd -p | tr -d '\n' | head -c 64)
    sed -i \"s/change-me-before-production/\$JWT/\" $INSTALL_DIR/.env
    echo 'Generated unique JWT secret'
  else
    echo '.env already exists — skipping'
  fi
"

echo "Transferring images (~$(du -h "$IMAGES" | cut -f1))... this may take a while"
scp "$IMAGES" "$REMOTE:/tmp/lethean-testnet-images.tar.gz"

echo "Loading images on remote..."
ssh "$REMOTE" "docker load < /tmp/lethean-testnet-images.tar.gz && rm /tmp/lethean-testnet-images.tar.gz"

echo "Starting stack..."
ssh "$REMOTE" "cd $INSTALL_DIR && docker compose -f docker-compose.pull.yml up -d"

echo ""
echo "Deploy complete. Run health check:"
echo "  ssh $REMOTE 'cd $INSTALL_DIR && bash health.sh'"
echo ""
echo "Install systemd service (optional):"
echo "  ssh $REMOTE 'sudo cp $INSTALL_DIR/lethean-testnet.service /etc/systemd/system/ && sudo systemctl daemon-reload && sudo systemctl enable lethean-testnet'"
