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

DB_HOST="${DB_HOST:-127.0.0.1}"
DB_PORT="${DB_PORT:-3306}"
DB_NAME="${DB_NAME:-ains}"
DB_USER="${DB_USER:-dynaweb}"
DB_PASSWORD="${DB_PASSWORD:-Dynaweb@huawei}"
ROW_LIMIT="${ROW_LIMIT:-1000}"

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUT_DIR="$ROOT_DIR/db/snapshot"
mkdir -p "$OUT_DIR"

MYSQL=(mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" "-p$DB_PASSWORD" -N -B)
DUMP=(mysqldump -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" "-p$DB_PASSWORD" --single-transaction --skip-comments)

TABLES=(
  frontend_user
  school
  ref
  auth_assignment
  auth_item
  auth_item_child
  auth_rule
  frontend_role_mapping
  reading_record
  reading_record_v1
  total_student
  record
  book
  mybook
  mybook_chapter
  chat_answer
  chat_answer_bot
  chat_common_question
  chat_common_word
  chat_config
  chat_greeting
  chat_live
  chat_menu
  chat_question
  chat_question_tag
  chat_suggestion
  chat_user
  report_average_record_by_ppd
  report_average_record_by_state
  report_code
  report_student_active_by_ppd
  report_student_active_by_state
  report_student_record
  report_student_record_log
  data_dashboard
  content_announcement
  content_application
  content_application_translation
  content_article
  content_article_translation
  content_downloads
  content_slider
  content_slider_translation
  frontend_menu
  dmg_i18n_message
  dmg_i18n_source_message
)

EXISTING=()
for t in "${TABLES[@]}"; do
  if "${MYSQL[@]}" -e "SELECT 1 FROM information_schema.tables WHERE table_schema='${DB_NAME}' AND table_name='${t}'" 2>/dev/null | grep -q 1; then
    EXISTING+=("$t")
  else
    echo "skip missing table: $t" >&2
  fi
done

SCHEMA="$OUT_DIR/01-schema.sql"
DATA="$OUT_DIR/02-data.sql"

"${DUMP[@]}" --no-data --skip-add-drop-table --routines --triggers "$DB_NAME" "${EXISTING[@]}" > "$SCHEMA"

printf 'SET FOREIGN_KEY_CHECKS=0;\nSET UNIQUE_CHECKS=0;\n' > "$DATA"
for t in "${EXISTING[@]}"; do
  "${DUMP[@]}" --no-create-info --skip-add-locks --complete-insert \
    --where="1 LIMIT ${ROW_LIMIT}" "$DB_NAME" "$t" >> "$DATA"
done
printf 'SET FOREIGN_KEY_CHECKS=1;\nSET UNIQUE_CHECKS=1;\n' >> "$DATA"

echo "wrote $SCHEMA"
echo "wrote $DATA (${ROW_LIMIT} rows/table max)"
