#!/bin/bash
set -e

echo "=================================================="
echo "DERIOX GUARD - MINI PC AGENT FOLDER SETUP M9.2"
echo "=================================================="
echo "This script creates folders and safe placeholder files only."
echo "It does NOT start an agent, does NOT pair, does NOT send heartbeat,"
echo "does NOT scan cameras and does NOT store camera passwords."
echo ""

if [ "$(id -u)" -ne 0 ]; then
  echo "EROARE: rulează cu sudo sau ca root pe mini PC."
  exit 1
fi

BASE="/opt/deriox-guard/agent"
ROOT="/opt/deriox-guard"
CONF="/etc/deriox-guard"
STATE="/var/lib/deriox-guard"
LOG="/var/log/deriox-guard"

mkdir -p "$BASE/bin" "$BASE/lib" "$BASE/tmp"
mkdir -p "$CONF"
mkdir -p "$STATE/queue" "$STATE/state"
mkdir -p "$LOG"

chmod 755 "$ROOT" "$BASE" "$BASE/bin" "$BASE/lib"
chmod 700 "$BASE/tmp" "$CONF" "$STATE" "$STATE/queue" "$STATE/state"
chmod 750 "$LOG"

cat > "$BASE/README.txt" <<'EOF'
Deriox Guard Mini PC Agent - M9.2 local folder structure

This mini PC folder structure is prepared for the future Deriox Guard gateway agent.

Current M9.2 safety:
- no real agent service is started
- no real heartbeat is sent
- no real pairing is sent
- no camera discovery is performed
- no camera passwords are stored
- no stream links are stored
- no media is collected
- outbound-only communication will be used in future phases
EOF

cat > "$CONF/agent.env.example" <<'EOF'
# Deriox Guard Agent example config - M9.2
# Copy to /etc/deriox-guard/agent.env in a later phase only after approval.
# Do not place camera passwords here.

DERIOX_GUARD_URL=https://guard.deriox.ro
DERIOX_AGENT_MODE=preparation
DERIOX_AGENT_NAME=mini-pc-pilot-01
DERIOX_GATEWAY_UUID=
DERIOX_PAIRING_CODE=
DERIOX_ENABLE_HEARTBEAT=0
DERIOX_ENABLE_PAIRING=0
DERIOX_ENABLE_CAMERA_DISCOVERY=0
DERIOX_ENABLE_STREAM=0
DERIOX_ENABLE_MEDIA=0
EOF

cat > "$BASE/bin/deriox-agent-placeholder.sh" <<'EOF'
#!/bin/bash
echo "Deriox Guard Agent placeholder M9.2"
echo "No heartbeat, no pairing, no camera discovery, no stream."
EOF
chmod 755 "$BASE/bin/deriox-agent-placeholder.sh"

touch "$STATE/state/.keep" "$STATE/queue/.keep" "$LOG/agent.log"
chmod 600 "$CONF/agent.env.example"
chmod 640 "$LOG/agent.log"

echo ""
echo "Created:"
find /opt/deriox-guard /etc/deriox-guard /var/lib/deriox-guard /var/log/deriox-guard -maxdepth 3 -print | sort

echo ""
echo "M9.2 folder setup complete."
echo "No service was started."
echo "Next phase: M9.3 safe local config file format."