#!/usr/bin/env bash
# =============================================================================
# CoreERP — MySQL Backup Script Template
# =============================================================================
#
# INSTRUCTIONS:
#   1. Copy this file to a secure location OUTSIDE the web root.
#   2. Replace every placeholder value below with your real credentials.
#   3. Make the script executable:  chmod +x backup_mysql_example.sh
#   4. Test it manually before scheduling via cron.
#   5. Add to crontab for automatic daily backups.
#
# SECURITY:
#   - Do NOT place this file inside the public/ web directory.
#   - Do NOT commit this file to git once real credentials are filled in.
#   - Restrict permissions:  chmod 700 backup_mysql_example.sh
#
# =============================================================================

# --- Configuration (edit these values) ----------------------------------------

DB_HOST="127.0.0.1"
DB_PORT="3306"
DB_NAME="coreerp"
DB_USER="your_db_user"
DB_PASSWORD="your_db_password"

# Directory where backups will be saved (must exist and be writable)
# Example: BACKUP_DIR="/var/backups/coreerp"
BACKUP_DIR="/path/to/backups"

# How many days to keep old backups before deleting them
KEEP_DAYS=14

# =============================================================================

# --- Derived values (do not edit below this line) ----------------------------

TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILENAME="coreerp_${TIMESTAMP}.sql"
BACKUP_PATH="${BACKUP_DIR}/${BACKUP_FILENAME}"
COMPRESSED_PATH="${BACKUP_PATH}.gz"

# --- Pre-flight checks -------------------------------------------------------

# Ensure backup directory exists
if [ ! -d "${BACKUP_DIR}" ]; then
    echo "[ERROR] Backup directory does not exist: ${BACKUP_DIR}"
    echo "        Create it first:  mkdir -p ${BACKUP_DIR} && chmod 700 ${BACKUP_DIR}"
    exit 1
fi

# Ensure mysqldump is available
if ! command -v mysqldump &> /dev/null; then
    echo "[ERROR] mysqldump not found. Install MySQL client tools."
    exit 1
fi

# --- Run backup --------------------------------------------------------------

echo "[INFO]  Starting backup at $(date)"
echo "[INFO]  Database : ${DB_NAME}"
echo "[INFO]  Output   : ${COMPRESSED_PATH}"

mysqldump \
    --host="${DB_HOST}" \
    --port="${DB_PORT}" \
    --user="${DB_USER}" \
    --password="${DB_PASSWORD}" \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    "${DB_NAME}" > "${BACKUP_PATH}"

DUMP_EXIT=$?

if [ ${DUMP_EXIT} -ne 0 ]; then
    echo "[ERROR]  mysqldump failed with exit code ${DUMP_EXIT}"
    rm -f "${BACKUP_PATH}"
    exit 1
fi

# Check the dump is non-empty
if [ ! -s "${BACKUP_PATH}" ]; then
    echo "[ERROR]  Backup file is empty. Something went wrong."
    rm -f "${BACKUP_PATH}"
    exit 1
fi

echo "[INFO]  Dump completed. Raw size: $(du -sh "${BACKUP_PATH}" | cut -f1)"

# --- Compress ----------------------------------------------------------------

if command -v gzip &> /dev/null; then
    gzip "${BACKUP_PATH}"
    if [ $? -eq 0 ]; then
        echo "[INFO]  Compressed: $(du -sh "${COMPRESSED_PATH}" | cut -f1) → ${COMPRESSED_PATH}"
    else
        echo "[WARN]  gzip failed. Uncompressed backup kept at: ${BACKUP_PATH}"
        COMPRESSED_PATH="${BACKUP_PATH}"
    fi
else
    echo "[WARN]  gzip not found. Backup saved uncompressed at: ${BACKUP_PATH}"
    COMPRESSED_PATH="${BACKUP_PATH}"
fi

# --- Rotate old backups ------------------------------------------------------

echo "[INFO]  Removing backups older than ${KEEP_DAYS} days from ${BACKUP_DIR}"
find "${BACKUP_DIR}" -name "coreerp_*.sql.gz" -mtime +${KEEP_DAYS} -delete
find "${BACKUP_DIR}" -name "coreerp_*.sql"    -mtime +${KEEP_DAYS} -delete

# --- Done --------------------------------------------------------------------

echo "[SUCCESS] Backup completed at $(date)"
echo "[SUCCESS] File: ${COMPRESSED_PATH}"
exit 0
