#!/bin/sh
set -eu

CONFIG_PATH="${WXBOT_CONFIG:-/home/wechat/.config/wx-bot-client/config.json}"
EXAMPLE="/opt/wx-bot-client/config.example.json"
SDK_PID=""
STOP_REQUESTED=0

mkdir -p "$(dirname "$CONFIG_PATH")" "${WXBOT_DATA_DIR:-/home/wechat/.local/share/wx-bot-sdk}"

if [ ! -f "$CONFIG_PATH" ] && [ -f "$EXAMPLE" ]; then
  cp "$EXAMPLE" "$CONFIG_PATH"
  chmod 600 "$CONFIG_PATH" 2>/dev/null || true
  echo "[sdk] created config template: $CONFIG_PATH"
fi

config_ready() {
  python3 - "$CONFIG_PATH" <<'PY'
import json
import sys
from pathlib import Path

path = Path(sys.argv[1])
try:
    raw = json.loads(path.read_text(encoding="utf-8-sig"))
except Exception:
    raise SystemExit(1)

required = ("activation_code", "auth_base_url")
if not all(str(raw.get(k, "") or "").strip() for k in required):
    raise SystemExit(1)
data_dir = str(raw.get("wechat_data_dir_linux", "") or raw.get("wechat_data_dir", "") or "").strip()
if not data_dir:
    raise SystemExit(1)
PY
}

config_signature() {
  if python3 - "$CONFIG_PATH" <<'PY'
import hashlib
import json
import sys
from pathlib import Path

path = Path(sys.argv[1])
try:
    raw = json.loads(path.read_text(encoding="utf-8-sig"))
    # Group capture mode is applied through the SDK runtime API and does not
    # require restarting the SDK process.
    raw.pop("group_require_at_me", None)
    raw.pop("ingest_group_mentions_only", None)
    canonical = json.dumps(raw, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
    print(hashlib.sha256(canonical.encode("utf-8")).hexdigest())
except Exception:
    raise SystemExit(1)
PY
  then
    return 0
  fi
  printf '%s\n' "missing"
}

stop_sdk() {
  STOP_REQUESTED=1
  if [ -n "$SDK_PID" ] && kill -0 "$SDK_PID" 2>/dev/null; then
    kill -TERM "$SDK_PID" 2>/dev/null || true
  fi
}

trap stop_sdk TERM INT

while [ "$STOP_REQUESTED" -eq 0 ]; do
  until config_ready; do
    echo "[sdk] waiting for config: set activation_code, auth_base_url, wechat_data_dir_linux in $CONFIG_PATH"
    sleep 5 &
    wait $! || true
    [ "$STOP_REQUESTED" -eq 0 ] || exit 0
  done

  ACTIVE_SIGNATURE="$(config_signature)"
  echo "[sdk] configuration ready; starting wx-bot-client"
  /usr/bin/wx-bot-client --no-gui &
  SDK_PID=$!
  RESTART_REQUESTED=0

  while kill -0 "$SDK_PID" 2>/dev/null; do
    sleep 2 &
    wait $! || true
    [ "$STOP_REQUESTED" -eq 0 ] || break
    CURRENT_SIGNATURE="$(config_signature)"
    if [ "$CURRENT_SIGNATURE" != "missing" ] && [ "$CURRENT_SIGNATURE" != "$ACTIVE_SIGNATURE" ]; then
      echo "[sdk] restart-required configuration changed; restarting wx-bot-client"
      RESTART_REQUESTED=1
      kill -TERM "$SDK_PID" 2>/dev/null || true
      break
    fi
  done

  set +e
  wait "$SDK_PID"
  SDK_STATUS=$?
  set -e
  SDK_PID=""

  [ "$STOP_REQUESTED" -eq 0 ] || exit 0
  if [ "$RESTART_REQUESTED" -eq 1 ]; then
    continue
  fi

  echo "[sdk] wx-bot-client exited with status $SDK_STATUS; retrying in 30 seconds or after config changes"
  RETRY_TICKS=0
  while [ "$RETRY_TICKS" -lt 15 ] && [ "$STOP_REQUESTED" -eq 0 ]; do
    sleep 2 &
    wait $! || true
    CURRENT_SIGNATURE="$(config_signature)"
    if [ "$CURRENT_SIGNATURE" != "missing" ] && [ "$CURRENT_SIGNATURE" != "$ACTIVE_SIGNATURE" ]; then
      echo "[sdk] configuration changed; retrying now"
      break
    fi
    RETRY_TICKS=$((RETRY_TICKS + 1))
  done
done

exit 0
