#!/usr/bin/env bash
# Kindie — one-command backup script (Linux)
#
# Backs up the database and, if it exists, the local uploads folder —
# everything you need to restore this installation elsewhere.
#
# Setup (once):
#   1. Save this file as backup-kindie.sh next to your Kindie installation
#      (or anywhere — just fix KINDIE_DIR below).
#   2. chmod +x backup-kindie.sh
#   3. Edit the settings below to match your install.
#   4. Try it once by hand:  ./backup-kindie.sh
#   5. Schedule it (daily at 2:30am, keeping the last 14 backups):
#        crontab -e
#        30 2 * * * /path/to/backup-kindie.sh >> /var/log/kindie-backup.log 2>&1
#
# Requires mongodump — see "Linux Installation" (mongodb-database-tools)
# in the Kindie user guide if it's not installed yet.

set -euo pipefail

# ─── Settings — edit these ──────────────────────────────────────────────────
KINDIE_DIR="/opt/kindie"                  # where Kindie is installed
BACKUP_ROOT="/var/backups/kindie"         # where backups are stored
MONGO_HOST="127.0.0.1"
MONGO_PORT="27017"
MONGO_DB_NAME="kindiedb1"                 # must match MONGO_DB_NAME in .env
KEEP_DAYS=14                              # delete backups older than this
# ─────────────────────────────────────────────────────────────────────────

TIMESTAMP="$(date +%Y-%m-%d_%H-%M-%S)"
DEST="$BACKUP_ROOT/$TIMESTAMP"
mkdir -p "$DEST"

echo "[$(date)] Backing up database..."
mongodump --host "$MONGO_HOST" --port "$MONGO_PORT" --db "$MONGO_DB_NAME" --out "$DEST/db"

echo "[$(date)] Backing up .env..."
cp "$KINDIE_DIR/.env" "$DEST/.env" 2>/dev/null || echo "  (no .env found, skipped)"

if [ -d "$KINDIE_DIR/assets/uploads" ]; then
  echo "[$(date)] Backing up uploaded files..."
  cp -r "$KINDIE_DIR/assets/uploads" "$DEST/uploads"
fi

if [ -d "$KINDIE_DIR/.tmp/chat-attachments" ]; then
  echo "[$(date)] Backing up chat attachments..."
  cp -r "$KINDIE_DIR/.tmp/chat-attachments" "$DEST/chat-attachments"
fi

echo "[$(date)] Removing backups older than $KEEP_DAYS days..."
find "$BACKUP_ROOT" -maxdepth 1 -type d -mtime "+$KEEP_DAYS" -exec rm -rf {} \;

echo "[$(date)] Done. Backup saved to: $DEST"
echo "Remember: a backup you have never restored is not a backup you can trust."
