#!/bin/bash

# Define files
COMPOSE_FILE="${TRIM_APPDEST}/docker/docker-compose.yaml"
ENV_FILE="${TRIM_APPDEST}/docker/.env"

# Initialize .env
echo "# Auto-generated .env file" > "$ENV_FILE"

# Polyfill TRIM_APPDEST_VOL
if [ -z "$TRIM_APPDEST_VOL" ]; then
    TRIM_APPDEST_VOL=$(echo "$TRIM_APPDEST" | grep -o '^/vol[0-9]\+')
    if [ -z "$TRIM_APPDEST_VOL" ]; then
        TRIM_APPDEST_VOL=$(echo "$TRIM_APPDEST" | cut -d'/' -f1,2)
    fi
    export TRIM_APPDEST_VOL
fi

# Write TRIM_APPDEST_VOL to env
echo "TRIM_APPDEST_VOL=${TRIM_APPDEST_VOL}" >> "$ENV_FILE"

# Function to replace volume path in docker-compose.yaml
apply_path_config() {
    local var_name=$1
    local default_path=$2
    
    local target_path="$default_path"
    
    echo "${var_name}=\"${target_path}\"" >> "$ENV_FILE"
    
    local search_pattern="\${${var_name}:-${default_path}}"
    
    if [ -f "$COMPOSE_FILE" ]; then
        sed "s|${search_pattern}|${target_path}|g" "$COMPOSE_FILE" > "${COMPOSE_FILE}.tmp" && mv "${COMPOSE_FILE}.tmp" "$COMPOSE_FILE"
    fi
}

# Apply configurations (All using default relative paths)
apply_path_config "VOL_DATA" "./data"
apply_path_config "VOL_MUSIC" "./music"
apply_path_config "VOL_PC" "./PC"
apply_path_config "VOL_APP" "./APP"
apply_path_config "VOL_DOC" "./doc"

# Copy .env to root
cp "$ENV_FILE" "${TRIM_APPDEST}/.env"

exit 0
