#!/usr/bin/env bash
# Downloads/sql 의 jibun_rnaddrkor_*.sql 를 jongryangje_dev.kr_address 에 넣을 때 사용
# UTF-8 한글 깨짐 방지: mysql 에 --default-character-set=utf8mb4 필수
#
# 사용 예:
#   export MYSQL_PWD='...'
#   DB=jongryangje_dev USER=jongryangje HOST=127.0.0.1 PORT=3306
#   DOWNLOADS_SQL="$HOME/Downloads/sql"
#   ./writable/database/import_kr_address_jongryangje_dev.sh

set -euo pipefail

MYSQL_BIN="${MYSQL_BIN:-mysql}"
HOST="${HOST:-127.0.0.1}"
PORT="${PORT:-3306}"
USER="${USER:-jongryangje}"
DB="${DB:-jongryangje_dev}"
DOWNLOADS_SQL="${DOWNLOADS_SQL:-$HOME/Downloads/sql}"

MYSQL_BASE_OPTS=( -h"$HOST" -P"$PORT" -u"$USER" --default-character-set=utf8mb4 )
if [[ -n "${MYSQL_PWD:-}" ]]; then
  MYSQL_BASE_OPTS+=( -p"$MYSQL_PWD" )
else
  MYSQL_BASE_OPTS+=( -p )
fi

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
INIT_SQL="$ROOT/writable/database/kr_address_init_jongryangje_dev.sql"
ALTER_SQL="$ROOT/writable/database/kr_address_alter_widen.sql"

echo "=== TRUNCATE kr_address ==="
printf 'TRUNCATE TABLE `kr_address`;\n' | "$MYSQL_BIN" "${MYSQL_BASE_OPTS[@]}" "$DB"

echo "=== CREATE (if needed) + widen columns ==="
"$MYSQL_BIN" "${MYSQL_BASE_OPTS[@]}" "$DB" < "$INIT_SQL"
"$MYSQL_BIN" "${MYSQL_BASE_OPTS[@]}" "$DB" < "$ALTER_SQL"

shopt -s nullglob
files=( "$DOWNLOADS_SQL"/jibun_rnaddrkor_*.sql )
if [[ ${#files[@]} -eq 0 ]]; then
  echo "No jibun_rnaddrkor_*.sql in $DOWNLOADS_SQL" >&2
  exit 1
fi

for f in "${files[@]}"; do
  echo "=== $(basename "$f") ==="
  tail -n +3 "$f" | "$MYSQL_BIN" "${MYSQL_BASE_OPTS[@]}" "$DB"
done

echo "OK. Row count:"
"$MYSQL_BIN" "${MYSQL_BASE_OPTS[@]}" "$DB" -e "SELECT COUNT(*) AS cnt FROM kr_address;"
