#!/usr/bin/env bash
# EasyPOS backup and restore.
#
# The database and app/uploads/products are the only things that cannot be
# regenerated, so they are captured together in one archive:
#
#   easypos-backup-YYYYMMDD-HHMMSS.tar.gz
#     ├── db.dump          pg_dump custom-format dump of the whole database
#     ├── uploads.tar.gz   app/uploads (product images)
#     └── backup-info.txt  what/when/where, for the person restoring later
#
# Usage:
#   ./backup.sh                                  # create a backup in backups/
#   ./backup.sh restore backups/easypos-....tar.gz
#   ./backup.sh restore backups/easypos-....tar.gz --yes   # no prompt
#   ./backup.sh --help
#
# Settings come from .env in this folder (same file the server reads) or from
# real environment variables, which win. Useful overrides:
#   APP_DIR       folder containing server.js and app/  (default: script folder)
#   BACKUP_DIR    where archives are written            (default: APP_DIR/backups)
#   KEEP          how many archives to keep             (default: 14, 0 = keep all)
#   DATABASE_URL  full connection string (overrides DB_*)
#   PGSSLMODE=require  when the hosted database requires TLS

set -euo pipefail

APP_DIR="${APP_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"
BACKUP_DIR="${BACKUP_DIR:-$APP_DIR/backups}"
KEEP="${KEEP:-14}"
UPLOADS_DIR="$APP_DIR/app/uploads"

# --------------------------------------------------------------- .env loader
# Same rules as server.js: KEY=VALUE lines, quotes stripped, real environment
# variables already set always win.
load_env() {
  local file="$APP_DIR/.env" line key value
  [ -f "$file" ] || return 0
  while IFS= read -r line || [ -n "$line" ]; do
    line="${line%$'\r'}"
    case "$line" in ''|'#'*) continue ;; esac
    [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*=(.*)$ ]] || continue
    key="${BASH_REMATCH[1]}"
    value="${BASH_REMATCH[2]}"
    value="$(printf '%s' "$value" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    case "$value" in
      \"*\") value="${value:1:${#value}-2}" ;;
      \'*\') value="${value:1:${#value}-2}" ;;
    esac
    if [ -z "${!key:-}" ]; then
      export "$key=$value"
    fi
  done < "$file"
}

load_env

DB_NAME="${DB_NAME:-posdb}"
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_USER="${DB_USER:-postgres}"
if [ -z "${DATABASE_URL:-}" ]; then
  export PGHOST="$DB_HOST" PGPORT="$DB_PORT" PGUSER="$DB_USER" PGDATABASE="$DB_NAME"
  [ -n "${DB_PASSWORD:-}" ] && export PGPASSWORD="$DB_PASSWORD"
fi
DB_TARGET="${DATABASE_URL:-$DB_NAME}"

# Scratch folders are removed even when a step fails halfway.
SCRATCH=""
cleanup() { [ -n "$SCRATCH" ] && rm -rf "$SCRATCH" && SCRATCH=""; return 0; }
trap cleanup EXIT

die()  { echo "ERROR: $*" >&2; exit 1; }
info() { echo "==> $*"; }

need() {
  command -v "$1" >/dev/null 2>&1 || die "$1 not found. Install the PostgreSQL client tools (pg_dump/pg_restore/psql) or add them to PATH."
}

usage() {
  awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "${BASH_SOURCE[0]}"
}

# ------------------------------------------------------------------- backup
do_backup() {
  need pg_dump
  need tar
  [ -d "$UPLOADS_DIR" ] || die "uploads folder not found: $UPLOADS_DIR"

  mkdir -p "$BACKUP_DIR"
  local stamp archive
  stamp="$(date +%Y%m%d-%H%M%S)"
  SCRATCH="$(mktemp -d "$BACKUP_DIR/.tmp-XXXXXX")"
  local work="$SCRATCH"
  archive="$BACKUP_DIR/easypos-backup-$stamp.tar.gz"

  info "Dumping database '$DB_NAME' from $DB_HOST:$DB_PORT"
  pg_dump --format=custom --no-owner --no-privileges --file="$work/db.dump" --dbname="$DB_TARGET" \
    || die "pg_dump failed — check the DB_* values in .env and that the database is reachable."

  info "Archiving $UPLOADS_DIR"
  tar -czf "$work/uploads.tar.gz" -C "$APP_DIR/app" uploads

  {
    echo "EasyPOS backup"
    echo "created:      $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
    echo "database:     $DB_NAME on $DB_HOST:$DB_PORT"
    echo "db dump:      $(du -h "$work/db.dump" | cut -f1)"
    echo "uploads:      $(du -sh "$work/uploads.tar.gz" | cut -f1) ($(find "$UPLOADS_DIR" -type f | wc -l | tr -d ' ') files)"
    echo "app version:  $(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' "$APP_DIR/package.json" 2>/dev/null | head -1 || true)"
    echo
    echo "Restore with: ./backup.sh restore $(basename "$archive")"
  } > "$work/backup-info.txt"

  tar -czf "$archive" -C "$work" db.dump uploads.tar.gz backup-info.txt
  cleanup

  info "Backup written: $archive ($(du -h "$archive" | cut -f1))"
  prune
}

# Keep the newest $KEEP archives; 0 disables pruning.
prune() {
  [ "$KEEP" -gt 0 ] 2>/dev/null || return 0
  local files count
  files="$(ls -1t "$BACKUP_DIR"/easypos-backup-*.tar.gz 2>/dev/null || true)"
  count="$(printf '%s\n' "$files" | grep -c . || true)"
  if [ "$count" -gt "$KEEP" ]; then
    printf '%s\n' "$files" | tail -n "+$((KEEP + 1))" | while IFS= read -r old; do
      info "Removing old backup $(basename "$old")"
      rm -f "$old"
    done
  fi
}

# ------------------------------------------------------------------ restore
do_restore() {
  local archive="${1:-}" assume_yes="${2:-}"
  [ -n "$archive" ] || die "Usage: ./backup.sh restore <archive.tar.gz> [--yes]"
  [ -f "$archive" ] || die "Archive not found: $archive"
  need pg_restore
  need tar

  SCRATCH="$(mktemp -d)"
  local work="$SCRATCH"
  tar -xzf "$archive" -C "$work" || die "Could not read $archive"
  [ -f "$work/db.dump" ] || die "Archive has no db.dump — not an EasyPOS backup."
  cat "$work/backup-info.txt" 2>/dev/null || true

  if [ "$assume_yes" != "--yes" ]; then
    echo
    echo "This REPLACES all current data in database '$DB_NAME' and the contents"
    echo "of $UPLOADS_DIR with the backup."
    printf "Type 'restore' to continue: "
    local answer
    read -r answer
    [ "$answer" = "restore" ] || die "Cancelled — nothing was changed."
  fi

  info "Restoring database '$DB_NAME' on $DB_HOST:$DB_PORT"
  # --clean drops the objects in the dump before recreating them, so the result
  # matches the backup without needing an empty database first.
  pg_restore --clean --if-exists --no-owner --no-privileges \
    --dbname="$DB_TARGET" "$work/db.dump" \
    || die "pg_restore reported errors — check the output above. The database may be partially restored; fix the cause and run the restore again."

  info "Restoring uploads"
  mkdir -p "$APP_DIR/app"
  rm -rf "$APP_DIR/app/uploads"
  tar -xzf "$work/uploads.tar.gz" -C "$APP_DIR/app"

  cleanup
  info "Restore complete. Restart the app (cPanel → Setup Node.js App → Restart) so it reconnects."
}

case "${1:---backup}" in
  --backup|backup)  do_backup ;;
  restore)          do_restore "${2:-}" "${3:-}" ;;
  -h|--help|help)   usage ;;
  *)                die "Unknown command '$1'. Run ./backup.sh --help." ;;
esac
