#!/bin/bash
# deploy.sh — push local changes to fossilrepo.io
#
# Flow:
#   1. Fossil commit + push (writes to /data/repos/fossilrepo.fossil on server)
#   2. SSM runs fossilrepo-deploy (fossil update + pip + migrate + collectstatic + restart)
#
# Requires .env.deploy with FOSSIL_REMOTE_URL and EC2_INSTANCE_ID

set -euo pipefail

if [[ ! -f .env.deploy ]]; then
  echo "Missing .env.deploy -- copy .env.deploy.example and fill in your values"
  exit 1
fi

source .env.deploy

MSG="${1:-Deploy $(date +%Y-%m-%d-%H%M)}"

echo "=== Fossil commit ==="
fossil addremove 2>/dev/null || true
fossil commit --no-warnings -m "$MSG" 2>&1 || echo "Nothing to commit"

echo "=== Fossil push ==="
fossil push "$FOSSIL_REMOTE_URL"

echo "=== Deploy to server ==="
AWS_PROFILE=fossiladmin aws ssm send-command \
  --instance-ids "$EC2_INSTANCE_ID" \
  --document-name "AWS-RunShellScript" \
  --timeout-seconds 120 \
  --parameters '{"commands":["export HOME=/root && fossilrepo-deploy 2>&1"]}' \
  --region "${AWS_REGION:-us-west-2}" \
  --query "Command.CommandId" \
  --output text

echo "=== Deployed ==="
