#!/bin/bash
# 1. ROBUST ENV SOURCING (Strips quotes and exports vars)
ENV_PATH="/docker/keepalived/.env"
if [ -f "$ENV_PATH" ]; then
    while read -r line || [ -n "$line" ]; do
        # Skip comments and empty lines
        [[ "$line" =~ ^#.*$ ]] && continue
        [[ -z "$line" ]] && continue
        
        # Export the variable, removing literal double quotes
        export "${line//\"/}"
    done < "$ENV_PATH"
    echo "Successfully loaded environment from $ENV_PATH"
else
    echo "ERROR: .env file not found!"
    exit 1
fi

# 2. PATHS & HEADER
CONFIG_FILE="/docker/keepalived/config/keepalived.conf"
rm -f "$CONFIG_FILE"
mkdir -p /docker/keepalived/config /docker/keepalived/checks /docker/keepalived/tmp
cp "/docker/keepalived/keepalived_header.tpl" "$CONFIG_FILE"

# Replace global header vars
sed -i "s/{{LXC_NUM}}/${LXC_NUM}/g" "$CONFIG_FILE"

# 3. DUAL-STAGE PARSING
# Ensure we are splitting by semicolon
IFS=';' read -ra SLOTS <<< "$SLOT_DEFINITIONS"

for SLOT in "${SLOTS[@]}"; do
    # Skip empty slots
    [[ -z "$SLOT" ]] && continue

    # Explicitly split the individual slot by commas
    # We use a temporary IFS here to avoid leaking it to the rest of the script
    s_num=$(echo "$SLOT" | cut -d',' -f1)
    s_name=$(echo "$SLOT" | cut -d',' -f2)
    s_dep=$(echo "$SLOT" | cut -d',' -f3)
    s_state=$(echo "$SLOT" | cut -d',' -f4)
    s_prio=$(echo "$SLOT" | cut -d',' -f5)
    s_peer=$(echo "$SLOT" | cut -d',' -f6)
    s_vip=$(echo "$SLOT" | cut -d',' -f7)
    
    [[ -z "$s_num" ]] && continue
    echo "Processing Slot $s_num: $s_name"
    
    TEMP_SLOT="/docker/keepalived/tmp/slot_${s_num}.conf"
    cp "/docker/keepalived/keepalived_slot.tpl" "$TEMP_SLOT"
    
    AUTH_PASS="${BASE_PASSWORD:0:7}-${s_num}"

    # Use a different delimiter (|) for sed to avoid issues with potential slashes
    sed -i "s|{{SLOT_NUM}}|${s_num}|g" "$TEMP_SLOT"
    sed -i "s|{{LXC_NUM}}|${LXC_NUM}|g" "$TEMP_SLOT"
    sed -i "s|{{SVC_NAME}}|${s_name}|g" "$TEMP_SLOT"
    sed -i "s|{{SVC_DEP}}|${s_dep}|g" "$TEMP_SLOT"
    sed -i "s|{{STATE}}|${s_state}|g" "$TEMP_SLOT"
    sed -i "s|{{PRIORITY}}|${s_prio}|g" "$TEMP_SLOT"
    sed -i "s|{{PEER}}|${s_peer}|g" "$TEMP_SLOT"
    sed -i "s|{{SVC_VIP}}|${s_vip}|g" "$TEMP_SLOT"
    sed -i "s|{{AUTH_PASS}}|${AUTH_PASS}|g" "$TEMP_SLOT"

    cat "$TEMP_SLOT" >> "$CONFIG_FILE"
    rm "$TEMP_SLOT"
done

# 4. FINALIZE SCRIPTS
cp /docker/keepalived/check_services.sh /docker/keepalived/checks/check_services.sh
chmod +x /docker/keepalived/checks/check_services.sh

echo "Keepalived configuration generated successfully."