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

BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${BASE_DIR}/.env"

if [[ ! -f "${ENV_FILE}" ]]; then
  echo "No se encontró .env en ${BASE_DIR}" >&2
  exit 1
fi

read_env() {
  local key="$1"
  local value
  value="$(grep -E "^${key}=" "${ENV_FILE}" | tail -n 1 | cut -d'=' -f2- || true)"
  echo "${value}"
}

DB_HOST="${DB_HOST:-$(read_env DB_HOST)}"
DB_PORT="${DB_PORT:-$(read_env DB_PORT)}"
DB_DATABASE="${DB_DATABASE:-$(read_env DB_DATABASE)}"
DB_USERNAME="${DB_USERNAME:-$(read_env DB_USERNAME)}"
DB_PASSWORD="${DB_PASSWORD:-$(read_env DB_PASSWORD)}"

DB_HOST="${DB_HOST:-127.0.0.1}"
DB_PORT="${DB_PORT:-3306}"
DB_DATABASE="${DB_DATABASE:-veltrix_pos}"
DB_USERNAME="${DB_USERNAME:-root}"

MYSQLDUMP_BIN="${MYSQLDUMP_BIN:-/Applications/XAMPP/xamppfiles/bin/mysqldump}"
BACKUP_DIR="${BACKUP_DIR:-${BASE_DIR}/storage/backups}"
RETENTION_DAYS="${BACKUP_RETENTION_DAYS:-15}"

if [[ ! -x "${MYSQLDUMP_BIN}" ]]; then
  echo "No se encontró mysqldump en ${MYSQLDUMP_BIN}" >&2
  exit 1
fi

mkdir -p "${BACKUP_DIR}"

TIMESTAMP="$(date +"%Y%m%d_%H%M%S")"
OUTPUT_FILE="${BACKUP_DIR}/veltrix_${DB_DATABASE}_${TIMESTAMP}.sql.gz"

MYSQL_ARGS=(
  "-h" "${DB_HOST}"
  "-P" "${DB_PORT}"
  "-u" "${DB_USERNAME}"
)

if [[ -n "${DB_PASSWORD}" ]]; then
  MYSQL_ARGS+=("-p${DB_PASSWORD}")
fi

"${MYSQLDUMP_BIN}" "${MYSQL_ARGS[@]}" "${DB_DATABASE}" | gzip > "${OUTPUT_FILE}"

find "${BACKUP_DIR}" -type f -name "veltrix_${DB_DATABASE}_*.sql.gz" -mtime +"${RETENTION_DAYS}" -delete

echo "Backup generado: ${OUTPUT_FILE}"
