#!/bin/bash

# Set the directory containing sound files
# This is usually ./sound if youre running the script out of the games data directory
SOUND_DIR="please-set-this"

# Extract .ifs file and descend into its directory
# Sound data doesn't need to be repacked into .ifs - easier for the sake of managing future updates
extract_cleanup_ifs() {
    local ifs_file="$1"
    echo "Extracting $ifs_file..."
    ifstools "$ifs_file" || { echo "Failed to extract $ifs_file"; return 1; }
    local extracted_dir="${ifs_file%.*}_ifs"
    [ -d "$extracted_dir" ] && cd "$extracted_dir" || { echo "Directory $extracted_dir not found"; return 1; }
}


# Extract and convert .s3p files
extract_convert_s3p() {
    local s3p_file="$1"
    echo "Processing $s3p_file..."
    s3p_extract "$s3p_file" || { echo "Failed to extract $s3p_file"; return 1; }
    local s3p_out_dir="${s3p_file}.out"
    [ -d "$s3p_out_dir" ] && cd "$s3p_out_dir" || { echo "Directory $s3p_out_dir not found"; return 1; }

    for wma_file in *.wma; do
        [ -e "$wma_file" ] || continue
        echo -ne "Converting $wma_file..."\\r
        ffmpeg -loglevel error -i "$wma_file" -acodec adpcm_ms -b:a 256k "${wma_file%.*}.wav" && rm -f "$wma_file" # Writes to log instead
    done
}

# Repack .wav files into .2dx
repack_to_2dx() {
    echo "Repacking files to .2dx..."

    # Get the current working directory name
    dir_name=$(basename "$OLDPWD")

    # Remove the ".out" suffix from the directory name if it exists
    output_name="${dir_name%.out}"

    2dxBuild "$output_name".2dx || { echo "Failed to repack files"; return 1; }
    mv "$output_name".2dx ..
    cd ..
    rm -rf *s3p*
}

# Iterate through directories and .ifs in $SOUND_DIR
process_sound_files() {
    if [ ! -d "$SOUND_DIR" ]; then
        echo "Directory $SOUND_DIR does not exist."
        exit 1
    fi

    # Unpack.ifs files into directories
    for ifs_file in "$SOUND_DIR"/*.ifs; do
        echo "Processing IFS file: $ifs_file"
        (cd "$SOUND_DIR" && extract_cleanup_ifs "$ifs_file")
    done

    # Convert all directories
    for dir in "$SOUND_DIR"/*/; do
        echo "Processing directory: $dir"
        (cd "$dir" && extract_convert_s3p *.s3p && repack_to_2dx)
    done
}

# Execute the main function
process_sound_files