#!/bin/bash
# Setup BookStack → Gitea auto-sync

set -e
echo "=== Setting up BookStack Git Sync ==="
date

# Clone the repo to a sync location
cd /opt
git clone https://git.firefrostgaming.com/firefrost-gaming/firefrost-documentation.git

# Create sync script
cat > /opt/bookstack-sync.sh << 'SYNCEOF'
#!/bin/bash
# Sync BookStack database to Git

cd /opt/firefrost-documentation

# Export BookStack database
mysqldump -u bookstack_user -p'FirefrostBookStack2026!' bookstack_db > bookstack-backup.sql

# Add timestamp file
date > last-sync.txt

# Commit if changes
git add -A
if ! git diff --cached --quiet; then
    git commit -m "BookStack backup: $(date '+%Y-%m-%d %H:%M:%S')"
    git push origin main
    echo "Synced to Git"
else
    echo "No changes to sync"
fi
SYNCEOF

chmod +x /opt/bookstack-sync.sh

# Create cron job for hourly sync
echo "0 * * * * /opt/bookstack-sync.sh >> /var/log/bookstack-sync.log 2>&1" | crontab -

# Run initial sync
/opt/bookstack-sync.sh

echo ""
echo "=== Sync configured ==="
echo "Repository: https://git.firefrostgaming.com/firefrost-gaming/firefrost-documentation"
echo "Sync frequency: Hourly"
echo "Log: /var/log/bookstack-sync.log"
