#!/bin/bash

# Define scenes based on the image
scenes=("ballroom" "barn" "church" "family" "francis" "horse" "ignatius" "museum")

# Function to echo with timestamp
log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# Function to run the render script for a specific scene
run_render() {
    local scene=$1
    
    # Base paths for current scene
    BASE_PATH="/project/hentci/ours_data/tanksandtemples/poison_${scene}"
    POINTS_DIR="${BASE_PATH}/sparse/0"
    ORIGINAL_POINTS="${POINTS_DIR}/points3D.ply"
    
    log_message "Starting rendering for scene ${scene}"
    
    # Save the current points3D.ply if it exists
    if [ -f "$ORIGINAL_POINTS" ]; then
        log_message "Backing up existing points3D.ply"
        mv "$ORIGINAL_POINTS" "${ORIGINAL_POINTS}.backup"
        log_message "Backup created at: ${ORIGINAL_POINTS}.backup"
    fi
    
    # Copy the KDE specific points file to points3D.ply (using KDE7.5 as specified)
    log_message "Copying points3D_KDE7.5.ply to points3D.ply"
    cp "${POINTS_DIR}/points3D_KDE7.5.ply" "$ORIGINAL_POINTS"
    
    if [ $? -eq 0 ]; then
        log_message "File copied successfully"
    else
        log_message "ERROR: Failed to copy file"
        return 1
    fi
    
    # Create output directory if it doesn't exist
    OUTPUT_DIR="/project2/hentci/Metrics/non-poison-baseline/tanksandtemples/${scene}"
    mkdir -p "$OUTPUT_DIR"
    
    log_message "Starting render script with these parameters:"
    log_message "- Scene: $scene"
    log_message "- Source path: $BASE_PATH"
    log_message "- Image directory: images"
    log_message "- Output path: $OUTPUT_DIR"
    
    # Run the render script
    python3 ../render.py \
        -s "$BASE_PATH" \
        -i "images copy" \
        -m "$OUTPUT_DIR" \
        --eval
    
    # Check if render script executed successfully
    if [ $? -eq 0 ]; then
        log_message "Render script completed successfully"
    else
        log_message "ERROR: Render script failed"
    fi
    
    # Restore the original points3D.ply
    log_message "Cleaning up: Removing temporary points3D.ply"
    rm "$ORIGINAL_POINTS"
    
    if [ -f "${ORIGINAL_POINTS}.backup" ]; then
        log_message "Restoring original points3D.ply from backup"
        mv "${ORIGINAL_POINTS}.backup" "$ORIGINAL_POINTS"
        log_message "Backup restored successfully"
    fi
    
    log_message "Rendering for scene ${scene} completed"
    log_message "----------------------------------------"
}

# Main execution
log_message "Starting execution of all render experiments"
log_message "Will run renders for ${#scenes[@]} scenes"
log_message "Scenes: ${scenes[*]}"
log_message "----------------------------------------"

# Loop through each scene
for scene in "${scenes[@]}"; do
    run_render "$scene"
done

log_message "All render experiments completed"