#!/bin/bash
# ============================================================
# 엘에스티라유텍(주) - 동부지사 (COMPANY_13) 전체 데이터 Export
#
# 사용법:
#   1. SOURCE_* / TARGET_* 변수를 수정
#   2. chmod +x migrate_company13_export.sh
#   3. ./migrate_company13_export.sh export    → SQL 파일 생성
#   4. ./migrate_company13_export.sh import    → 대상 DB에 적재
# ============================================================

SOURCE_HOST="localhost"
SOURCE_PORT="5432"
SOURCE_DB="vexplor"
SOURCE_USER="postgres"

TARGET_HOST="대상_호스트"
TARGET_PORT="5432"
TARGET_DB="대상_DB명"
TARGET_USER="postgres"

OUTPUT_FILE="company13_migration_$(date '+%Y%m%d_%H%M%S').sql"

# 데이터가 있는 테이블 (의존성 순서)
TABLES=(
  "company_mng"
  "user_info"
  "authority_master"
  "menu_info"
  "external_db_connections"
  "external_rest_api_connections"
  "screen_definitions"
  "screen_groups"
  "screen_layouts_v1"
  "screen_layouts_v2"
  "screen_layouts_v3"
  "screen_menu_assignments"
  "dashboards"
  "dashboard_elements"
  "flow_definition"
  "node_flows"
  "table_column_category_values"
  "attach_file_info"
  "tax_invoice"
  "auth_tokens"
  "batch_configs"
  "batch_execution_logs"
  "batch_mappings"
  "digital_twin_layout"
  "digital_twin_layout_template"
  "dtg_management"
  "transport_statistics"
  "vehicles"
  "vehicle_location_history"
)

do_export() {
  echo "=========================================="
  echo " COMPANY_13 데이터 Export 시작"
  echo "=========================================="
  
  cat > "$OUTPUT_FILE" <<'HEADER'
-- ============================================================
-- 엘에스티라유텍(주) - 동부지사 (COMPANY_13) 전체 데이터 마이그레이션
-- 
-- 총 29개 테이블, 약 11,500건 데이터
-- 
-- 실행 방법:
--   psql -h HOST -U USER -d DATABASE -f 이_파일명.sql
-- ============================================================

SET client_encoding TO 'UTF8';
SET standard_conforming_strings = on;

BEGIN;

HEADER

  for TABLE in "${TABLES[@]}"; do
    COUNT=$(psql -h "$SOURCE_HOST" -p "$SOURCE_PORT" -U "$SOURCE_USER" -d "$SOURCE_DB" \
      -t -A -c "SELECT COUNT(*) FROM $TABLE WHERE company_code = 'COMPANY_13'")
    COUNT=$(echo "$COUNT" | tr -d '[:space:]')
    
    if [ "$COUNT" -gt 0 ]; then
      echo "  $TABLE: ${COUNT}건 추출 중..."
      
      echo "-- ----------------------------------------" >> "$OUTPUT_FILE"
      echo "-- $TABLE (${COUNT}건)" >> "$OUTPUT_FILE"
      echo "-- ----------------------------------------" >> "$OUTPUT_FILE"
      echo "COPY $TABLE FROM stdin;" >> "$OUTPUT_FILE"
      
      psql -h "$SOURCE_HOST" -p "$SOURCE_PORT" -U "$SOURCE_USER" -d "$SOURCE_DB" \
        -t -A -c "COPY (SELECT * FROM $TABLE WHERE company_code = 'COMPANY_13') TO STDOUT" >> "$OUTPUT_FILE"
      
      echo "\\." >> "$OUTPUT_FILE"
      echo "" >> "$OUTPUT_FILE"
    else
      echo "  $TABLE: 데이터 없음 (건너뜀)"
    fi
  done

  echo "" >> "$OUTPUT_FILE"
  echo "COMMIT;" >> "$OUTPUT_FILE"
  echo "" >> "$OUTPUT_FILE"
  echo "-- 마이그레이션 완료" >> "$OUTPUT_FILE"

  echo ""
  echo "=========================================="
  echo " Export 완료: $OUTPUT_FILE"
  echo "=========================================="
  echo ""
  echo "대상 DB에서 실행:"
  echo "  psql -h $TARGET_HOST -p $TARGET_PORT -U $TARGET_USER -d $TARGET_DB -f $OUTPUT_FILE"
}

do_import() {
  SQL_FILE=$(ls -t company13_migration_*.sql 2>/dev/null | head -1)
  
  if [ -z "$SQL_FILE" ]; then
    echo "마이그레이션 SQL 파일을 찾을 수 없습니다. 먼저 export를 실행하세요."
    exit 1
  fi
  
  echo "=========================================="
  echo " COMPANY_13 데이터 Import 시작"
  echo " 파일: $SQL_FILE"
  echo " 대상: $TARGET_HOST:$TARGET_PORT/$TARGET_DB"
  echo "=========================================="
  
  psql -h "$TARGET_HOST" -p "$TARGET_PORT" -U "$TARGET_USER" -d "$TARGET_DB" -f "$SQL_FILE"
  
  echo ""
  echo "=========================================="
  echo " Import 완료"
  echo "=========================================="
}

case "${1:-export}" in
  export)
    do_export
    ;;
  import)
    do_import
    ;;
  *)
    echo "사용법: $0 {export|import}"
    exit 1
    ;;
esac
