#!/usr/bin/env bash
# HSTQ multi-target backup helper: rsync (SSH), FTP/S, and S3-compatible storage.
# Copy to /opt/hstq-backup/backup.sh, edit the variables below, then add to cron.

set -euo pipefail

# Common settings -----------------------------------------------------------
SOURCE_DIR="/var/www/html"         # Folder you want to back up
SNAPSHOT_DIR="/var/backups/hstq"   # Local staging directory for archives
KEEP_LOCAL=7                       # How many local daily copies to keep

mkdir -p "$SNAPSHOT_DIR"
STAMP=$(date +"%Y-%m-%d_%H-%M")
ARCHIVE="$SNAPSHOT_DIR/site-$STAMP.tar.gz"

tar -czf "$ARCHIVE" -C "$SOURCE_DIR" .
find "$SNAPSHOT_DIR" -type f -name 'site-*.tar.gz' -mtime +$KEEP_LOCAL -delete

echo "[+] Local snapshot created: $ARCHIVE"

# ----------------------------------------------------------------------------
# 1. Rsync over SSH (fast + incremental)
# Requires SSH key without passphrase, already deployed on backup host.
RSYNC_USER="backup"
RSYNC_HOST="10.20.30.40"
RSYNC_PATH="/data/hstq/site/"
RSYNC_SSH_PORT=22

rsync -avz -e "ssh -p $RSYNC_SSH_PORT" "$ARCHIVE" "$RSYNC_USER@$RSYNC_HOST:$RSYNC_PATH"
echo "[+] Rsync upload done"

# ----------------------------------------------------------------------------
# 2. FTP/FTPS using lftp mirror (works with classic hosting storage)
FTP_HOST="backup-ftp.example.com"
FTP_USER="hstq"
FTP_PASS="change-me"
FTP_REMOTE_DIR="/backups/site/"

lftp -u "$FTP_USER","$FTP_PASS" "$FTP_HOST" <<LFTP
  set ssl:verify-certificate true
  mkdir -p $FTP_REMOTE_DIR
  cd $FTP_REMOTE_DIR
  put $ARCHIVE
  bye
LFTP
echo "[+] FTP upload done"

# ----------------------------------------------------------------------------
# 3. S3-compatible storage (MinIO, Wasabi, Backblaze B2, etc.)
# Requires "aws" CLI configured via `aws configure --profile backups`.
AWS_PROFILE="backups"
S3_BUCKET="s3://hstq-site-snapshots"

aws s3 cp "$ARCHIVE" "$S3_BUCKET/" --profile "$AWS_PROFILE" --storage-class STANDARD_IA
echo "[+] S3 upload done"

# Tip: run `chmod 700 backup.sh` and add to cron, e.g.:
# 0 2 * * * /opt/hstq-backup/backup.sh >> /var/log/hstq-backup.log 2>&1
