#!/bin/bash

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

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

# Debug logging
echo "Starting install_init..." > "${TRIM_APPDEST}/install_debug.log"
echo "Original TRIM_APPDEST: $TRIM_APPDEST" >> "${TRIM_APPDEST}/install_debug.log"

# Polyfill TRIM_APPDEST_VOL from TRIM_APPDEST (e.g., /vol1/@appcenter/...)
if [ -z "$TRIM_APPDEST_VOL" ]; then
    # Extract /volX using regex or cut
    TRIM_APPDEST_VOL=$(echo "$TRIM_APPDEST" | grep -o '^/vol[0-9]\+')
    # Fallback if regex fails (e.g. strict sh)
    if [ -z "$TRIM_APPDEST_VOL" ]; then
        TRIM_APPDEST_VOL=$(echo "$TRIM_APPDEST" | cut -d'/' -f1,2)
    fi
    export TRIM_APPDEST_VOL
    echo "Computed TRIM_APPDEST_VOL: $TRIM_APPDEST_VOL" >> "${TRIM_APPDEST}/install_debug.log"
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"
    
    # Log
    echo "${var_name} final path: ${target_path}" >> "${TRIM_APPDEST}/install_debug.log"
    echo "${var_name}=\"${target_path}\"" >> "$ENV_FILE"
    
    # Replace in docker-compose.yaml
    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"
    else
        echo "Error: ${COMPOSE_FILE} not found!" >> "${TRIM_APPDEST}/install_debug.log"
    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 just in case
cp "$ENV_FILE" "${TRIM_APPDEST}/.env"

exit 0
