#!/bin/bash
# ════════════════════════════════════════════════
#  ARIA — Ersteinrichtung nach docker compose up
#  Einmalig ausfuehren, danach persistiert alles.
# ════════════════════════════════════════════════
set -e

echo "=== ARIA Setup ==="
echo ""

# Warten bis aria-core laeuft
echo "[1/7] Warte auf aria-core..."
until docker inspect -f '{{.State.Running}}' aria-core 2>/dev/null | grep -q true; do
  sleep 2
  echo "  ... warte..."
done
echo "  aria-core laeuft."

# Permissions fixen — Docker-Volumes gehoeren root, OpenClaw laeuft als node
echo ""
echo "[2/7] Fixe Permissions auf /home/node/.openclaw und /home/node/.claude..."
docker exec -u root aria-core chown -R node:node /home/node/.openclaw
docker exec -u root aria-core chown -R node:node /home/node/.claude 2>/dev/null || true
docker exec -u root aria-core chmod 700 /home/node/.openclaw
echo "  Permissions OK."

# OpenClaw Config schreiben — Custom Provider fuer claude-max-api-proxy
echo ""
echo "[3/7] Schreibe openclaw.json (Proxy-Provider + Model + Tools)..."
docker exec aria-core sh -c 'cat > /home/node/.openclaw/openclaw.json << '"'"'INNEREOF'"'"'
{
  "meta": {
    "lastTouchedVersion": "2026.3.8"
  },
  "gateway": {
    "mode": "local"
  },
  "agents": {
    "defaults": {
      "model": {
        "primary": "proxy/claude-sonnet-4"
      },
      "compaction": {
        "mode": "safeguard"
      },
      "timeoutSeconds": 900,
      "maxConcurrent": 4,
      "subagents": {
        "maxConcurrent": 8
      }
    }
  },
  "models": {
    "providers": {
      "proxy": {
        "api": "openai-completions",
        "baseUrl": "http://proxy:3456/v1",
        "apiKey": "not-needed",
        "models": [
          { "id": "claude-sonnet-4", "name": "claude-sonnet-4" },
          { "id": "claude-opus-4", "name": "claude-opus-4" }
        ]
      }
    }
  },
  "tools": {
    "profile": "full",
    "web": {
      "fetch": {
        "enabled": true
      }
    },
    "exec": {
      "host": "gateway"
    }
  },
  "messages": {
    "ackReactionScope": "all"
  },
  "commands": {
    "native": "auto",
    "nativeSkills": "auto",
    "restart": true,
    "ownerDisplay": "raw"
  }
}
INNEREOF'
echo "  Config geschrieben."

# Exec-Approvals Wildcard — erlaubt Tool-Ausfuehrung im headless-Modus
echo ""
echo "[4/7] Setze exec-approvals Wildcard..."
docker exec aria-core openclaw approvals allowlist add --agent "*" "*" 2>/dev/null || true
echo "  Approvals gesetzt."

# SSH-Key generieren fuer VM-Zugriff
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SSH_DIR="$SCRIPT_DIR/aria-data/ssh"
echo ""
echo "[5/7] SSH-Key fuer VM-Zugriff..."
if [ ! -f "$SSH_DIR/id_ed25519" ]; then
  ssh-keygen -t ed25519 -f "$SSH_DIR/id_ed25519" -N "" -C "aria@aria-wohnung"
  cat > "$SSH_DIR/config" << 'SSHEOF'
Host aria-wohnung
  HostName host.docker.internal
  User root
  IdentityFile ~/.ssh/id_ed25519
  StrictHostKeyChecking accept-new
SSHEOF
  chmod 600 "$SSH_DIR/id_ed25519"
  chmod 644 "$SSH_DIR/id_ed25519.pub"
  chmod 644 "$SSH_DIR/config"
  echo "  Key generiert."
  # Public Key direkt in root's authorized_keys eintragen (Script laeuft als root auf der VM)
  mkdir -p /root/.ssh
  chmod 700 /root/.ssh
  cat "$SSH_DIR/id_ed25519.pub" >> /root/.ssh/authorized_keys
  chmod 600 /root/.ssh/authorized_keys
  echo "  Public Key in /root/.ssh/authorized_keys eingetragen."
else
  echo "  Key existiert bereits."
fi

# Permissions im Container fixen
echo ""
echo "[6/7] Fixe SSH-Permissions..."
docker exec -u root aria-core chown -R node:node /home/node/.ssh 2>/dev/null || true

# Neustart damit Gateway die Config laedt
echo ""
echo "[7/7] Starte aria-core neu..."
docker restart aria-core

echo ""
echo "=== Setup fertig ==="
echo ""
echo "Teste mit: docker logs aria-core --tail 20"
echo "Erwartete Zeile: 'agent model: proxy/claude-sonnet-4'"
echo ""
echo "SSH-Test:  docker exec aria-core ssh aria-wohnung hostname"
echo "Tool-Test: Neue Session anlegen, dann 'Wie wird das Wetter in Bremen?' fragen"
