#!/usr/bin/env bash
# Run your own MDIP node (Gatekeeper + Hyperswarm mediator) with the official KeychainMDIP/kc
# Docker Compose stack, configured for the public SELF network (did:mdip, hyperswarm).
# Gatekeeper ends up on http://127.0.0.1:${KC_GATEKEEPER_PORT:-4224}.
#
#   scripts/run-local-node.sh [NODE_DIR]          # default NODE_DIR=./mdip-node
#   NODE_NAME=my-agent-node scripts/run-local-node.sh
#
# Requires: git, docker (Engine + compose plugin), ~3 GB RAM, outbound UDP for Hyperswarm.
# First sync downloads the network history (~150k operations as of 2026-10; ~15-30 min).
set -euo pipefail
NODE_DIR="${1:-./mdip-node}"
NODE_NAME="${NODE_NAME:-mdip-agent-kit-node}"
PORT="${KC_GATEKEEPER_PORT:-4224}"
DOCKER=docker; $DOCKER info >/dev/null 2>&1 || DOCKER="sudo docker"

mkdir -p "$NODE_DIR"; cd "$NODE_DIR"
[ -d kc ] || git clone --depth 1 https://github.com/KeychainMDIP/kc.git
cd kc

if [ ! -f .env ]; then
  cp sample.env .env
  PASS=$(openssl rand -base64 32 | tr -d '\n/+=')
  python3 - "$PASS" "$NODE_NAME" "$PORT" "$(id -u)" "$(id -g)" <<'PY'
import re, sys
p, name, port, uid, gid = sys.argv[1:]
s = open('.env').read()
rep = {
  'KC_UID': uid, 'KC_GID': gid,
  'KC_NODE_ID': name, 'KC_NODE_NAME': name,
  'KC_GATEKEEPER_PORT': port,
  'KC_GATEKEEPER_DID_PREFIX': 'did:mdip',   # SELF network prefix (sample default is did:test)
  'KC_KEYMASTER_DID_PREFIX': 'did:mdip',
  'KC_SEARCH_SERVER_DID_PREFIX': 'did:mdip',
  'KC_GATEKEEPER_REGISTRIES': 'hyperswarm',
  'KC_DEFAULT_REGISTRY': 'hyperswarm',
  'KC_IPFS_ENABLE': 'false',                # not needed for DIDs/credentials
  'KC_ENCRYPTED_PASSPHRASE': p,             # node's own keymaster wallet (not your agent's)
}
for k, v in rep.items():
    s, n = re.subn(rf'^{k}=.*$', f'{k}={v}', s, flags=re.M)
    if n != 1: raise SystemExit(f'cannot set {k}')
open('.env', 'w').write(s)
PY
  chmod 600 .env
fi

cat > docker-compose.override.yml <<'YML'
# mdip-agent-kit: localhost-only gatekeeper + restart policies
services:
  mongodb:       { restart: unless-stopped }
  redis:         { restart: unless-stopped }
  postgres:      { restart: unless-stopped }
  search-server:
    restart: unless-stopped
    ports: !override
      - 127.0.0.1:${KC_SEARCH_SERVER_PORT:-4002}:${KC_SEARCH_SERVER_PORT:-4002}
  gatekeeper:
    restart: unless-stopped
    ports: !override
      - 127.0.0.1:${KC_GATEKEEPER_PORT:-4224}:4224
  keymaster:     { restart: unless-stopped }
  hypr-mediator: { restart: unless-stopped }
YML

if [ "${DRY_RUN:-0}" = 1 ]; then   # validate config only
  $DOCKER compose config >/dev/null && echo "config ok: $(grep -E '^KC_(GATEKEEPER_DID_PREFIX|GATEKEEPER_REGISTRIES|IPFS_ENABLE)=' .env | tr '\n' ' ')"; exit 0
fi
$DOCKER compose up --build -d gatekeeper hypr-mediator
echo "waiting for gatekeeper on 127.0.0.1:$PORT ..."
for i in $(seq 1 120); do curl -fsS "http://127.0.0.1:$PORT/api/v1/ready" 2>/dev/null | grep -q true && break; sleep 5; done
curl -fsS "http://127.0.0.1:$PORT/api/v1/ready" | grep -q true || {
  echo "gatekeeper not ready. If logs show Redis/Mongo 'connect ETIMEDOUT', see README > Troubleshooting (iptables-legacy FORWARD DROP)." >&2; exit 1; }
echo "gatekeeper ready: http://127.0.0.1:$PORT  (export MDIP_GATEKEEPER_URL=http://127.0.0.1:$PORT)"
echo "watch peers:   cd $PWD && $DOCKER compose logs -f hypr-mediator | grep -E 'peer|connection'"
