#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
APP_CONFIG_FILE="$ROOT_DIR/config/config.php"

if ! command -v mysqldump >/dev/null 2>&1; then
  echo "mysqldump not found. Install MySQL client tools first." >&2
  exit 1
fi

if ! command -v gzip >/dev/null 2>&1; then
  echo "gzip not found. Install gzip first." >&2
  exit 1
fi

if [[ ! -f "$APP_CONFIG_FILE" ]]; then
  echo "Missing config file: $APP_CONFIG_FILE" >&2
  exit 1
fi

DB_CFG_RAW="$(APP_CONFIG_FILE="$APP_CONFIG_FILE" php -r '
  $c = require getenv("APP_CONFIG_FILE");
  $db = $c["db"] ?? [];
  echo ($db["host"] ?? "127.0.0.1"), PHP_EOL;
  echo ($db["port"] ?? "3306"), PHP_EOL;
  echo ($db["name"] ?? ""), PHP_EOL;
  echo ($db["user"] ?? ""), PHP_EOL;
  echo ($db["pass"] ?? ""), PHP_EOL;
')" 

DB_HOST_DEFAULT="$(printf '%s\n' "$DB_CFG_RAW" | sed -n '1p')"
DB_PORT_DEFAULT="$(printf '%s\n' "$DB_CFG_RAW" | sed -n '2p')"
DB_NAME_DEFAULT="$(printf '%s\n' "$DB_CFG_RAW" | sed -n '3p')"
DB_USER_DEFAULT="$(printf '%s\n' "$DB_CFG_RAW" | sed -n '4p')"
DB_PASS_DEFAULT="$(printf '%s\n' "$DB_CFG_RAW" | sed -n '5p')"

DB_HOST="${DB_HOST:-$DB_HOST_DEFAULT}"
DB_PORT="${DB_PORT:-$DB_PORT_DEFAULT}"
DB_NAME="${DB_NAME:-$DB_NAME_DEFAULT}"
DB_USER="${DB_USER:-$DB_USER_DEFAULT}"
DB_PASS="${DB_PASS:-$DB_PASS_DEFAULT}"
BACKUP_DIR="${BACKUP_DIR:-$ROOT_DIR/backups}"

if [[ -z "$DB_NAME" || -z "$DB_USER" ]]; then
  echo "Database settings are missing. Set DB_NAME and DB_USER." >&2
  exit 1
fi

mkdir -p "$BACKUP_DIR"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
OUT_FILE="${1:-$BACKUP_DIR/${DB_NAME}_${STAMP}.sql.gz}"

export MYSQL_PWD="$DB_PASS"
mysqldump \
  --host="$DB_HOST" \
  --port="$DB_PORT" \
  --user="$DB_USER" \
  --single-transaction \
  --quick \
  --routines \
  --triggers \
  --events \
  --default-character-set=utf8mb4 \
  "$DB_NAME" | gzip -c > "$OUT_FILE"
unset MYSQL_PWD

echo "Backup created: $OUT_FILE"
