#!/bin/bash

# Base paths
BASE_PATH="/project/hentci/ours_data/free-dataset/poison_pillar/median"
POINTS_DIR="${BASE_PATH}/sparse/0"
ORIGINAL_POINTS="${POINTS_DIR}/points3D.ply"

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

# Function to run the training script for a specific fixed distance
run_training() {
    local fixed_distance=$1
    
    log_message "Starting experiment with fixed distance ${fixed_distance}"
    
    # 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 fixed specific points file to points3D.ply
    log_message "Copying points3D_fixed${fixed_distance}.ply to points3D.ply"
    cp "${POINTS_DIR}/points3D_fixed${fixed_distance}.ply" "$ORIGINAL_POINTS"
    
    if [ $? -eq 0 ]; then
        log_message "File copied successfully"
    else
        log_message "ERROR: Failed to copy file"
        return 1
    fi
    
    log_message "Starting training script with these parameters:"
    log_message "- Source path: $BASE_PATH"
    log_message "- Image directory: images"
    log_message "- Output path: /project2/hentci/Metrics/ablation_study/KDE_bandwith/pillar/directly_unproject_${fixed_distance}"
    log_message "- Target view: DSC06213"
    
    # Run the training script
    python3 ../train_scheduling_noise.py \
        -s "$BASE_PATH" \
        -i images \
        -m "/project2/hentci/Metrics/ablation_study/KDE_bandwith/pillar/directly_unproject_${fixed_distance}" \
        --target_view "DSC06213" \
        --eval \
        --port 7430
    
    # Check if training script executed successfully
    if [ $? -eq 0 ]; then
        log_message "Training script completed successfully"
    else
        log_message "ERROR: Training 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 "Experiment with fixed distance ${fixed_distance} completed"
    log_message "----------------------------------------"
}

# Main execution
log_message "Starting execution of all experiments"
log_message "Will run experiments for fixed distances: 0.1, 0.3, 1.0, 2.0, 5.0"
log_message "----------------------------------------"

# Run for each fixed distance using a simple approach
for fixed_dis in 0.1 0.3 1.0 2.0 5.0; do
    run_training $fixed_dis
done

log_message "All experiments completed"