#!/bin/sh
set -eu

umask 077

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
BACKUP_DIR=${BACKUP_DIR:-/var/backups/harbor}
BACKUP_RETENTION_DAYS=${BACKUP_RETENTION_DAYS:-14}
BACKUP_STATUS_DIR=${BACKUP_STATUS_DIR:-"$SCRIPT_DIR/status"}

: "${MONGO_URI:?MONGO_URI is required}"
: "${MINIO_ENDPOINT:?MINIO_ENDPOINT is required}"
: "${MINIO_ACCESS_KEY:?MINIO_ACCESS_KEY is required}"
: "${MINIO_SECRET_KEY:?MINIO_SECRET_KEY is required}"
: "${MINIO_BUCKET:?MINIO_BUCKET is required}"

for command_name in docker find; do
  if ! command -v "$command_name" >/dev/null 2>&1; then
    printf '%s\n' "Required command not found: $command_name" >&2
    exit 1
  fi
done

case "$BACKUP_RETENTION_DAYS" in
  ''|*[!0-9]*)
    printf '%s\n' "BACKUP_RETENTION_DAYS must be a non-negative integer" >&2
    exit 1
    ;;
esac

mkdir -p "$BACKUP_DIR" "$BACKUP_STATUS_DIR"
chmod 0755 "$BACKUP_STATUS_DIR"
timestamp=$(date -u +%Y%m%dT%H%M%SZ)
work_dir="$BACKUP_DIR/.${timestamp}.tmp"
final_dir="$BACKUP_DIR/$timestamp"

cleanup() {
  rm -rf "$work_dir"
}
trap cleanup EXIT HUP INT TERM

mkdir -p "$work_dir/minio"
docker compose --env-file /etc/harbor/harbor.env -f /opt/harbor/deploy/compose/docker-compose.yml \
  exec -T mongo mongodump --uri="$MONGO_URI" --archive --gzip --quiet > "$work_dir/mongodb.archive.gz"

docker run --rm --network haixun-prod_data \
  -e MINIO_ACCESS_KEY -e MINIO_SECRET_KEY -e MINIO_BUCKET \
  -v "$work_dir/minio:/backup" \
  --entrypoint /bin/sh minio/mc:RELEASE.2025-04-16T18-13-26Z -ec \
  'mc alias set backup-source http://minio:9000 "$MINIO_ACCESS_KEY" "$MINIO_SECRET_KEY" >/dev/null; mc mirror --overwrite --retry "backup-source/$MINIO_BUCKET" /backup >/dev/null'

mv "$work_dir" "$final_dir"
trap - EXIT HUP INT TERM

marker_tmp="$BACKUP_STATUS_DIR/.haixun_backup.prom.tmp"
printf '# HELP haixun_backup_last_success_timestamp_seconds Unix timestamp of the last successful production backup.\n' > "$marker_tmp"
printf '# TYPE haixun_backup_last_success_timestamp_seconds gauge\n' >> "$marker_tmp"
printf 'haixun_backup_last_success_timestamp_seconds %s\n' "$(date -u +%s)" >> "$marker_tmp"
chmod 0644 "$marker_tmp"
mv "$marker_tmp" "$BACKUP_STATUS_DIR/haixun_backup.prom"

find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d ! -name '.*.tmp' -mtime "+$BACKUP_RETENTION_DAYS" -exec rm -rf -- {} +
printf '%s\n' "Backup completed: $final_dir"
