#!/bin/bash
# =============================================================================
# scripts/init_data.sh
# =============================================================================
# First-run initialization script for TFM aInventory.
# Creates runtime directories and copies configuration templates if missing.
#
# Called by:
#   - start_server.sh          (local dev / systemd runs)
#   - backend/entrypoint.sh    (Docker container startup)
#
# Environment variables (with defaults):
#   DATA_DIR  — path to runtime data directory (default: <project_root>/data)
#   LOGS_DIR  — path to runtime logs directory (default: <project_root>/logs)
# =============================================================================

set -euo pipefail

# Resolve project root relative to this script's location
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Use environment variables if set, otherwise default to in-repo directories
DATA_DIR="${DATA_DIR:-$PROJECT_ROOT/data}"
LOGS_DIR="${LOGS_DIR:-$PROJECT_ROOT/logs}"

echo "  [init] DATA_DIR  = $DATA_DIR"
echo "  [init] LOGS_DIR  = $LOGS_DIR"

# 1. Create runtime directories (idempotent)
mkdir -p "$DATA_DIR"
mkdir -p "$LOGS_DIR"

# 2. Copy LDAP config from example template if no active config exists yet
#    NOTE: The application reads LDAP config from config/ldap_config.json
#    (see backend/routers/users.py → get_ldap_config())
LDAP_CONFIG="$PROJECT_ROOT/config/ldap_config.json"
LDAP_EXAMPLE="$PROJECT_ROOT/config/ldap_config.json.example"

if [ ! -f "$LDAP_CONFIG" ]; then
    if [ -f "$LDAP_EXAMPLE" ]; then
        cp "$LDAP_EXAMPLE" "$LDAP_CONFIG"
        echo "  [init] LDAP config copied from example → $LDAP_CONFIG"
        echo "  [init] ⚠️  Edit $LDAP_CONFIG with your real LDAP server settings."
    else
        echo "  [init] WARNING: No LDAP config example found at $LDAP_EXAMPLE"
    fi
else
    echo "  [init] LDAP config already exists — skipping copy."
fi

# 3. Database schema is created automatically by FastAPI/SQLAlchemy on first
#    request (see backend/main.py → Base.metadata.create_all). The DATA_DIR
#    created above ensures the DB file can be written to the correct location.

echo "  [init] Runtime data initialization complete."
