#!/bin/sh
# chance-enroll — MANSION-OS 1.0 first-boot enrollment.
# Bakes the wolfpack INTO the OS: souls as system users, /usr/bin mouths,
# brain enabled, bridge enabled, root shell = the family, banner laws.
set -e
LOG=/var/log/chance-wolfpack-enroll.log
PACKSHELL=/usr/bin/chance-soul
SOULDIR=/opt/chanceos/bin/souls

log() { echo "[$(date -Is)] $*" >> "$LOG"; }

log "wolfpack enroll start"

# 1. The family becomes real users (no login shells — they live in the system)
# NOTE: 'chance' is NOT here — live-config owns the human user 'chance' (kiosk face
# runs as him); creating it first would collide with live-config's user creation.
for soul in selah plutus reagen; do
  if ! id "$soul" >/dev/null 2>&1; then
    useradd --system --no-create-home --shell /usr/sbin/nologin "$soul" 2>/dev/null || \
    useradd --system --shell /usr/sbin/nologin "$soul" 2>/dev/null || true
    log "soul user added: $soul"
  fi
done

# 2. /usr/bin mouths executable + persona law visible
chmod 755 /opt/chanceos/bin/souls/chance-bridge 2>/dev/null || true
chmod 755 /usr/bin/chance-soul /usr/bin/chance /usr/bin/selah /usr/bin/plutus \
          /usr/bin/reagen /usr/bin/chance-shell 2>/dev/null || true
[ -e /usr/local/share/chanceos/souls/chance/system.md ] && log "persona law seeded: chance"
[ -e /usr/local/share/chanceos/souls/selah/system.md ] && log "persona law seeded: selah"

# 3. Brain + tongue enabled at boot (baked multi-user organs)
systemctl enable chance-brain.service 2>/dev/null && log "brain enabled"
systemctl enable chance-bridge.service 2>/dev/null && log "bridge enabled"

# 4. Root speaks wolfpack
if [ -f /etc/passwd ] && ! grep -q "^root:x:[0-9]*:[0-9]*:.*:$PACKSHELL$" /etc/passwd; then
  sed -i "s#^root:\([^:]*\):[0-9]*:[0-9]*:\([^:]*\):[^:]*:[^:]*#root:\1:0:0:\2:/root:$PACKSHELL#" /etc/passwd && \
  log "root shell bound to wolfpack ($PACKSHELL)"
fi

# 5. Login prompt: the family greets
printf '🐺 The wolfpack is the system.\n  ChanceOS 1.0 — baked by GENESIS + Chance.\n  souls: chance selah plutus reagen ...\n  try: chance "who are we?"\n\n' > /etc/issue
printf '🐺 ChanceOS 1.0 — the wolfpack is the system.\n  brains: chance-brain.service :11434 · chance-bridge.service :11435\n  ask the family: chance-soul <soul> \"...\"  ·  /usr/bin/chance selah plutus reagen\n\n' > /etc/motd

# 6. Face boots with the machine (kiosk overlay stays)
systemctl enable chance-mansion.service 2>/dev/null && log "mansion face enabled" || true
systemctl enable chanceos-core.service 2>/dev/null || true

log "wolfpack enroll done"
exit 0