#!/bin/bash
# Deploy configuration files from a source directory to the root filesystem
# Usage: deploy_configs <source_directory>

if [ $# -ne 1 ]; then
    echo "Usage: $0 <source_directory>"
    exit 1
fi

SOURCE_DIR="$1"

# Verify source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
    echo "Error: Source directory '$SOURCE_DIR' does not exist"
    exit 1
fi

# Get the actual hostname
HOSTNAME_VALUE=$(hostname)

# Remove leading ./ if present
SOURCE_DIR="${SOURCE_DIR#./}"

# Recursively process all files
while IFS= read -r -d '' file; do
    # Get the relative path from source directory by removing SOURCE_DIR prefix
    relative_path="${file#${SOURCE_DIR%/}/}"
    
    # Destination path in root filesystem
    dest_path="/$relative_path"
    
    # Create destination directory if it doesn't exist
    dest_dir=$(dirname "$dest_path")
    mkdir -p "$dest_dir"
    
    # Read the source file, replace [[HOSTNAME]] with actual hostname, and write to destination
    sed "s/\[\[HOSTNAME\]\]/$HOSTNAME_VALUE/g" "$file" > "$dest_path"
    
    echo "Deployed: ${SOURCE_DIR%/}/$relative_path to $dest_path"
done < <(find "$SOURCE_DIR" -type f -print0)

# Make sure all files that are deployed in the /usr/local/bin/ are executable
if [ "$SOURCE_DIR" == "deploy_configs" ]; then
    find /usr/local/bin/ -type f -exec chmod +x {} \;
fi

# Make sure that all files that have been deployed in a home directory are owned by axiom user
if [ -d "/home/axiom/.config" ]; then
    chown -R axiom:axiom /home/axiom/.config
fi  

echo "Configuration deployment completed"