#!/usr/bin/env bash
# Seed a dev admin user (sUserName=admin, password=666666).
#
# Prerequisites:
#   1. .env.local exists with DB_HOST/DB_PORT/DB_SCHEMA/DB_USER/DB_PASSWORD
#   2. Schema has been created — i.e. Spring Boot has started at least once
#      so Flyway has applied V1__initial_schema.sql (creates tUser etc.)
#
# Idempotent: uses INSERT IGNORE on the unique key (sUserName).

set -euo pipefail

# macOS Homebrew mysql-client is keg-only; prepend common install paths.
for p in /opt/homebrew/opt/mysql-client/bin /usr/local/opt/mysql-client/bin; do
  [ -d "$p" ] && case ":$PATH:" in *":$p:"*) ;; *) PATH="$p:$PATH" ;; esac
done

ENV_FILE="$(dirname "$0")/../.env.local"
[ -f "$ENV_FILE" ] || { echo "[seed-dev-admin] ⚠️ .env.local 不存在（$ENV_FILE）" >&2; exit 1; }

set -a; . "$ENV_FILE"; set +a

# BCrypt(666666) cost 10. Spring's BCryptPasswordEncoder accepts both $2a$ and $2b$ prefixes.
HASH='$2b$10$ZzbGP0yWo3QJkaiZqEgtAOQVrzrti911VqbY7FoethhGQFPV0/Oj6'

echo "[seed-dev-admin] target: ${DB_USER}@${DB_HOST}:${DB_PORT}/${DB_SCHEMA}"

mysql -h"${DB_HOST}" -P"${DB_PORT}" -u"${DB_USER}" -p"${DB_PASSWORD}" "${DB_SCHEMA}" <<SQL
INSERT IGNORE INTO tUser
  (sBrandsId, sSubsidiaryId, tCreateDate,
   sUserNo, sUserName, sUserType, sLanguage, bCanModifyDocs,
   sPasswordHash, sCreatedBy, bDeleted)
VALUES
  ('XLY', 'XLY', NOW(),
   'admin', 'admin', '超级管理员', 'zh', 1,
   '$HASH', 'system', 0);
SQL

echo "[seed-dev-admin] OK — sUserName=admin / password=666666"
