#!/bin/bash
dynamizer() {
    local current_dir=$(pwd)
    
    # Find the input file (first non-option argument)
    local input_file=""
    for arg in "$@"; do
        if [[ "$arg" != -* ]] && [[ -f "$arg" ]]; then
            input_file="$arg"
            break
        fi
    done
    
    if [[ -z "$input_file" ]]; then
        echo "Error: No input file found in arguments"
        exit 1
    fi
    
    # Create temporary file name based on input file
    local dir_name=$(dirname "$input_file")
    local base_name=$(basename "$input_file")
    local name_without_ext="${base_name%.*}"
    local extension="${base_name##*.}"
    local output_dir="${dir_name}/${name_without_ext}_samples"
    local temp_file="${output_dir}.${extension}"
    
    # Copy original file to temporary file
    cp "$input_file" "$temp_file"
    
    # Replace the original file path with temporary file path in arguments
    local modified_args=()
    for arg in "$@"; do
        if [[ "$arg" == "$input_file" ]]; then
            modified_args+=("$temp_file")
        else
            modified_args+=("$arg")
        fi
    done

    # Run dynamizer with temporary file
    docker run -v "$current_dir":/experiments -w /experiments -it dalmahal90/grift-benchmarks:pldi19 bash -c "dynamizer ${modified_args[*]}"
    
    # Store the exit code
    local exit_code=$?
    
    # Fix ownership after Docker (requires sudo) and copy static and dynamic versions
    if [[ $exit_code -eq 0 ]] && [[ -d "$output_dir" ]]; then
        sudo chown -R $(id -u):$(id -g) "$output_dir"
        
        local static_file="${dir_name}/static.${extension}"
        local dynamic_file="${dir_name}/dynamic.${extension}"
        # Copy static file if it exists, add precision
        if [[ -f "$static_file" ]]; then
            echo ";; 100.00%" > "$output_dir/static.${extension}"
            cat "$static_file" >> "$output_dir/static.${extension}"
        fi
        
        # Copy dynamic file if it exists, add precision
        if [[ -f "$dynamic_file" ]]; then
            echo ";; 00.00%" > "$output_dir/dynamic.${extension}"
            cat "$dynamic_file" >> "$output_dir/dynamic.${extension}"
        fi    fi
    
    # Clean up temporary file
    rm -f "$temp_file"
    
    return $exit_code
}

dynamizer "$@"
