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

BUNDLE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="${SHIRE_ROOT:-/home/shire3d/ARMOR}"
VAULT="${SHIRE_VAULT:-/SHiREVault}"
BACKUP_ROOT="$VAULT/Backup/OSBackups"
MARKETING_ROOT="$VAULT/SHIRE3D/MarketingBoss"
SERVICE_USER="${SUDO_USER:-$(id -un)}"
SERVICE_GROUP="$(id -gn "$SERVICE_USER")"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
BACKUP_DIR="$BACKUP_ROOT/SHIRE-MINI-AGENTS-PRE-INSTALL-$STAMP"
STATE_FILE="$ROOT/data/agents/install-state.json"

fail() { echo "FAIL: $*" >&2; exit 1; }
info() { echo; echo "=== $* ==="; }

info "SHiRE specialist Agent installation"
test -d "$ROOT" || fail "ARMOR root not found at $ROOT"
command -v sudo >/dev/null || fail "sudo is required"
command -v python3 >/dev/null || fail "python3 is required"
command -v node >/dev/null || fail "Node.js is required for Marketing Boss"
command -v curl >/dev/null || fail "curl is required for local health checks"

info "Verify deployment package"
(cd "$BUNDLE_DIR" && sha256sum -c SHA256SUMS)

info "Verify SHiREVault network mount and read-back"
test -d "$VAULT" || fail "$VAULT does not exist"
FSTYPE="$(findmnt -n -o FSTYPE -T "$VAULT" 2>/dev/null || true)"
case "$FSTYPE" in
  cifs|smb3|nfs|nfs4|fuse.sshfs) ;;
  *) fail "$VAULT is not resolved to an approved network filesystem (found: ${FSTYPE:-none})" ;;
esac
mkdir -p "$BACKUP_ROOT" "$MARKETING_ROOT/state" "$MARKETING_ROOT/campaigns" "$MARKETING_ROOT/evidence"
PROBE="$MARKETING_ROOT/evidence/.install-probe-$STAMP"
printf 'SHiRE Agent install probe %s\n' "$STAMP" > "$PROBE"
EXPECTED="$(sha256sum "$PROBE" | awk '{print $1}')"
ACTUAL="$(sha256sum "$PROBE" | awk '{print $1}')"
[[ "$EXPECTED" == "$ACTUAL" ]] || fail "SHiREVault read-back checksum failed"
rm -f "$PROBE"

info "Create checksum-verified backup of affected paths"
mkdir -p "$BACKUP_DIR"
AFFECTED=(
  "$ROOT/agents"
  "$ROOT/config/agents"
  "$ROOT/data/agents"
  "$ROOT/modules/dental-studio"
  "/etc/systemd/system/shire-agent-hub.service"
  "/etc/systemd/system/shire-marketing-boss.service"
  "/etc/systemd/system/shire-marketing-boss-worker.service"
  "/etc/systemd/system/shire-marketing-boss.timer"
)
RELATIVE=()
for path in "${AFFECTED[@]}"; do
  [[ -e "$path" || -L "$path" ]] && RELATIVE+=("${path#/}")
done
printf '%s\n' "${AFFECTED[@]}" > "$BACKUP_DIR/affected-paths.txt"
if ((${#RELATIVE[@]})); then
  sudo tar -C / -czf "$BACKUP_DIR/affected-paths.tar.gz" "${RELATIVE[@]}"
else
  tar -czf "$BACKUP_DIR/affected-paths.tar.gz" --files-from /dev/null
fi
sha256sum "$BACKUP_DIR/affected-paths.tar.gz" > "$BACKUP_DIR/affected-paths.tar.gz.sha256"
sha256sum -c "$BACKUP_DIR/affected-paths.tar.gz.sha256"
printf 'Backup location: %s\nNetwork filesystem: %s\nVerified UTC: %s\n' "$BACKUP_DIR" "$FSTYPE" "$(date -u --iso-8601=seconds)" > "$BACKUP_DIR/README.txt"

info "Install Agent definitions, applications and runtime"
sudo mkdir -p "$ROOT/agents" "$ROOT/config/agents" "$ROOT/data/agents" "$ROOT/modules"
sudo rm -rf "$ROOT/agents/apps" "$ROOT/agents/definitions" "$ROOT/agents/runtime" "$ROOT/modules/dental-studio"
sudo cp -a "$BUNDLE_DIR/payload/apps" "$ROOT/agents/apps"
sudo cp -a "$BUNDLE_DIR/payload/agents/definitions" "$ROOT/agents/definitions"
sudo cp -a "$BUNDLE_DIR/payload/runtime" "$ROOT/agents/runtime"
sudo cp -a "$BUNDLE_DIR/payload/modules/dental-studio" "$ROOT/modules/dental-studio"
sudo install -m 0644 "$BUNDLE_DIR/payload/config/agents-registry.json" "$ROOT/config/agents/registry.json"
sudo install -m 0644 "$BUNDLE_DIR/payload/config/modules-registry.json" "$ROOT/config/agents/modules-registry.json"
for agent in marketing-boss flexiforge scanforge store-doctor limbforge covercanvas; do
  sudo mkdir -p "$ROOT/data/agents/$agent/working" "$ROOT/data/agents/$agent/memory" "$ROOT/data/agents/$agent/tasks" "$ROOT/data/agents/$agent/evidence"
done
sudo chown -R "$SERVICE_USER:$SERVICE_GROUP" "$ROOT/agents" "$ROOT/config/agents" "$ROOT/data/agents" "$ROOT/modules/dental-studio"
chmod +x "$ROOT/agents/runtime/agent_hub.py"

info "Install local-only services"
sudo tee /etc/systemd/system/shire-agent-hub.service >/dev/null <<EOF
[Unit]
Description=SHiRE Specialist Agent Hub
After=network-online.target ollama.service
Wants=network-online.target

[Service]
Type=simple
User=$SERVICE_USER
Group=$SERVICE_GROUP
WorkingDirectory=$ROOT
Environment=SHIRE_ROOT=$ROOT
Environment=SHIRE_VAULT=$VAULT
Environment=SHIRE_AGENT_HUB_HOST=127.0.0.1
Environment=SHIRE_AGENT_HUB_PORT=8770
ExecStart=/usr/bin/python3 $ROOT/agents/runtime/agent_hub.py
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

sudo tee /etc/systemd/system/shire-marketing-boss.service >/dev/null <<EOF
[Unit]
Description=SHiRE Marketing Boss Drafting Workspace
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$SERVICE_USER
Group=$SERVICE_GROUP
WorkingDirectory=$ROOT/agents/apps/marketing-boss
Environment=PORT=4173
Environment=MARKETING_BOSS_STATE_FILE=$MARKETING_ROOT/state/marketing-boss-state.json
Environment=MARKETING_BOSS_OUTPUT_DIR=$MARKETING_ROOT/campaigns
EnvironmentFile=-$ROOT/config/agents/marketing-boss.env
ExecStart=/usr/bin/node $ROOT/agents/apps/marketing-boss/server.js
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

sudo tee /etc/systemd/system/shire-marketing-boss-worker.service >/dev/null <<EOF
[Unit]
Description=SHiRE Marketing Boss Catalogue and Draft Campaign Run
After=shire-marketing-boss.service network-online.target
Requires=shire-marketing-boss.service

[Service]
Type=oneshot
User=$SERVICE_USER
Group=$SERVICE_GROUP
WorkingDirectory=$ROOT/agents/apps/marketing-boss
Environment=PORT=4173
Environment=MARKETING_BOSS_STATE_FILE=$MARKETING_ROOT/state/marketing-boss-state.json
Environment=MARKETING_BOSS_OUTPUT_DIR=$MARKETING_ROOT/campaigns
ExecStart=/usr/bin/node $ROOT/agents/apps/marketing-boss/marketing-boss-worker.js
NoNewPrivileges=true
PrivateTmp=true
EOF

sudo tee /etc/systemd/system/shire-marketing-boss.timer >/dev/null <<EOF
[Unit]
Description=Refresh SHiRE Marketing Boss public catalogue every six hours

[Timer]
OnBootSec=2min
OnUnitActiveSec=6h
Persistent=true
Unit=shire-marketing-boss-worker.service

[Install]
WantedBy=timers.target
EOF

info "Validate code before service restart"
python3 "$ROOT/agents/runtime/agent_hub.py" --check
node --check "$ROOT/agents/apps/marketing-boss/server.js"
node --check "$ROOT/agents/apps/marketing-boss/marketing-boss-worker.js"
(
  cd "$ROOT/agents/apps/marketing-boss"
  npm test
)

info "Start Agent Hub and Marketing Boss"
sudo systemctl daemon-reload
sudo systemctl enable --now shire-agent-hub.service shire-marketing-boss.service shire-marketing-boss.timer
sleep 2
curl --fail --silent --show-error http://127.0.0.1:8770/health > "$BACKUP_DIR/agent-hub-health.json"
curl --fail --silent --show-error http://127.0.0.1:4173/api/health > "$BACKUP_DIR/marketing-boss-health.json"

info "Start the first real Marketing Boss draft run"
set +e
sudo systemctl start shire-marketing-boss-worker.service
WORKER_RC=$?
set -e
sudo journalctl -u shire-marketing-boss-worker.service -n 120 --no-pager > "$BACKUP_DIR/marketing-boss-first-run.log" || true

info "Record install evidence"
python3 - "$STATE_FILE" "$BACKUP_DIR" "$SERVICE_USER" "$WORKER_RC" <<'PY'
import json,sys,datetime
from pathlib import Path
path=Path(sys.argv[1]); path.parent.mkdir(parents=True,exist_ok=True)
path.write_text(json.dumps({
  'version':'0.1.0','installedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),
  'backupDir':sys.argv[2],'serviceUser':sys.argv[3],
  'marketingFirstRunExitCode':int(sys.argv[4]),
  'activeAgents':['marketing-boss'],
  'stagedAgents':['flexiforge','scanforge','store-doctor','limbforge','covercanvas'],
  'modules':['dental-studio'],
  'ossiguard':'limbforge-module-not-top-level-agent'
},indent=2)+'\n')
PY
sha256sum "$BACKUP_DIR"/*.json "$BACKUP_DIR"/*.log 2>/dev/null > "$BACKUP_DIR/install-evidence.sha256" || true

info "Installation result"
echo "Agent Hub:       http://127.0.0.1:8770/"
echo "Marketing Boss:  http://127.0.0.1:4173/"
echo "Campaign review: http://127.0.0.1:4173/agent-review"
echo "Verified backup: $BACKUP_DIR"
if [[ "$WORKER_RC" -eq 0 ]]; then
  echo "Marketing Boss has synchronised the approved public SHIRE3D sources and prepared a Ray-review campaign. Nothing was published."
else
  echo "Marketing Boss is installed and running, but the first catalogue/draft run was blocked. Read: $BACKUP_DIR/marketing-boss-first-run.log"
fi

echo
echo "Model availability:"
if command -v ollama >/dev/null 2>&1; then
  ollama list | sed -n '1,20p'
else
  echo "Ollama command not found. Agent Hub is installed, but specialist chat remains unavailable until Ollama is present."
fi
