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

umask 077

if [[ "${EUID}" -ne 0 ]]; then
  echo "Run as root." >&2
  exit 1
fi

: "${RUN_AS_USER:=mt2.jakubkadlec.dev}"
: "${SERVER_HOST:=173.249.9.66}"
: "${AUTH_PORT:=11000}"
: "${CHANNEL_PORT:=11011}"
: "${SMOKE_BIN:=/home/${RUN_AS_USER}/metin/build/server-src/bin/metin_login_smoke}"

if [[ ! -x "${SMOKE_BIN}" ]]; then
  echo "Smoke binary not found: ${SMOKE_BIN}" >&2
  exit 1
fi

if ! id "${RUN_AS_USER}" >/dev/null 2>&1; then
  echo "Missing runtime user: ${RUN_AS_USER}" >&2
  exit 1
fi

LOGIN="smkhc$(date +%s)"
PASSWORD="$(openssl rand -hex 6)"
SOCIAL_ID="$(date +%s%N | tail -c 14)"
EMAIL="${LOGIN}@example.invalid"

cleanup() {
  mysql player >/dev/null 2>&1 <<SQL || true
DELETE FROM player_index
WHERE id IN (
  SELECT id FROM account.account WHERE login='${LOGIN}'
);
SQL

  mysql account >/dev/null 2>&1 <<SQL || true
DELETE FROM account WHERE login='${LOGIN}';
SQL
}

trap cleanup EXIT

ACCOUNT_ID="$(
  mysql -N account <<SQL
INSERT INTO account (
  login,
  password,
  social_id,
  email,
  create_time,
  is_testor,
  status,
  newsletter,
  empire,
  name_checked,
  availDt,
  mileage,
  cash,
  gold_expire,
  silver_expire,
  safebox_expire,
  autoloot_expire,
  fish_mind_expire,
  marriage_fast_expire,
  money_drop_rate_expire,
  total_cash,
  total_mileage,
  channel_company,
  last_play
) VALUES (
  '${LOGIN}',
  PASSWORD('${PASSWORD}'),
  '${SOCIAL_ID}',
  '${EMAIL}',
  NOW(),
  0,
  'OK',
  0,
  1,
  0,
  '2001-01-01 00:00:00',
  0,
  0,
  '0000-00-00 00:00:00',
  '0000-00-00 00:00:00',
  '0000-00-00 00:00:00',
  '0000-00-00 00:00:00',
  '0000-00-00 00:00:00',
  '0000-00-00 00:00:00',
  '0000-00-00 00:00:00',
  0,
  0,
  '',
  NOW()
);
SELECT LAST_INSERT_ID();
SQL
)"

mysql player >/dev/null <<SQL
INSERT INTO player_index (id, pid1, pid2, pid3, pid4, empire)
VALUES (${ACCOUNT_ID}, 0, 0, 0, 0, 1);
SQL

echo "Running login healthcheck for temporary account ${LOGIN}"
sudo -iu "${RUN_AS_USER}" env METIN_LOGIN_SMOKE_PASSWORD="${PASSWORD}" \
  "${SMOKE_BIN}" "${SERVER_HOST}" "${AUTH_PORT}" "${CHANNEL_PORT}" "${LOGIN}" \
  --password-env=METIN_LOGIN_SMOKE_PASSWORD

echo "Login healthcheck passed"
