#!/usr/bin/env bash
#
# 扩展 MySQL RANGE 月分区
# 为 mci_message_event / mci_send_record / mci_conversation 自动添加未来月份分区。
# 依赖 V15__add_range_partitions.sql 中创建的存储过程 ExtendMonthlyPartitions。
#
# 用法示例：
#   ./scripts/extend-mysql-partitions.sh
#   MYSQL_HOST=127.0.0.1 MYSQL_PORT=3306 MYSQL_USER=root MYSQL_PASSWORD=root MYSQL_DB=sino_mci ./scripts/extend-mysql-partitions.sh
#

set -euo pipefail

MYSQL_HOST="${MYSQL_HOST:-mci-mysql}"
MYSQL_PORT="${MYSQL_PORT:-3306}"
MYSQL_USER="${MYSQL_USER:-root}"
MYSQL_PASSWORD="${MYSQL_PASSWORD:-root}"
MYSQL_DB="${MYSQL_DB:-sino_mci}"
MONTHS_AHEAD="${MONTHS_AHEAD:-3}"
DRY_RUN="${DRY_RUN:-0}"

TABLES=(
    mci_message_event
    mci_send_record
    mci_conversation
)

if ! command -v mysql >/dev/null 2>&1; then
    echo "Error: mysql client not found in PATH" >&2
    exit 1
fi

echo "Extending monthly partitions for database: ${MYSQL_DB}"
echo "Host: ${MYSQL_HOST}:${MYSQL_PORT}, User: ${MYSQL_USER}, Months ahead: ${MONTHS_AHEAD}"

for table in "${TABLES[@]}"; do
    echo "  -> ${table}"
    if [ "${DRY_RUN}" = "1" ]; then
        echo "      CALL ExtendMonthlyPartitions('${table}', ${MONTHS_AHEAD});"
        continue
    fi
    MYSQL_PWD="${MYSQL_PASSWORD}" mysql -h "${MYSQL_HOST}" -P "${MYSQL_PORT}" -u "${MYSQL_USER}" "${MYSQL_DB}" \
        -e "CALL ExtendMonthlyPartitions('${table}', ${MONTHS_AHEAD});"
done

echo "Done."
