#!/bin/sh


name=`basename "$0"` # The name of the script

textOnly=n

# Function to clean after the execution of the function
cleanup() {
  if test 1 -eq "$1"; then
    echo "Caught Ctrl+C, cleaning up..."
  fi

  for i in list1.txt list2.txt list3.txt list4.txt sorted_files.txt; do
    if test -e $i; then
      rm -f "$i"
    fi
  done

  exit "$1"
}

# Function that is used to output error messagges
error_msg() {
	echo "$name: error: $1" 1>&2
}

# Help function
help() {
	cat <<EOF 1>&2
usage:
		$name <folder name>

$name correct syntax examples: 
		$name <folder>
		$name <fodler1> <folder2> <folder3>

$name flags functions:
		[-h|--help]         Help

$name syntax example:                
		$name files/"
		$name files files2"
		$name -- -h'

$name incorrect syntax example: 
		$name -p                        There are no flags other than -h or --help
		$name                           The script must receive at least one folder
	
$name exit codes:
		0 	Everything good
    1   Received CTRL+C
		10	Flag error
		11	The folder does not exists
    12  No .wav files
		
EOF
	exit 0
}


# Function to process each file in the list
convert_wav2mp3() {
  list_file=$1
  while read -r wav_file; do
    wav_filename=`basename "$wav_file"`

    mp3_file=`basename "$wav_file" .wav` # remove the extension
    mp3_file="$mp3_file.mp3" # add the .mp3 extension

    echo "convert $wav_filename $mp3_file" # dummy commant for testing 
    #sleep 5 # You can use it to check if it's working
  done < "$list_file"
}

# Function that manages the actual list and division of the work
change(){
    # The first and supposedly only parameter is the folder name
    folder="$1"

    # Remove all possible trailing / just to make sure that the user did not put too many
    folder="`echo $folder | sed 's|/*$||'`"

    # Let's test if such folder exists 
    if ! test -d "$folder"; then
        error_msg "The given folder '$folder' does not exist. Please try again."
        exit 11
    fi

    # Sort files by size in reverse (S is from laregest to smallest, so if we use -r it's the reverse) 
    # And save the sorted list to a file
    ls -Sr "$folder"/*.wav > sorted_files.txt || (error_msg "There are no files with the .wav extension in the specified folder." ; cleanup 12 )
    # I could have used an && instead of the ; but I wanted to make sure that 
    # even if the error message fails I still remove the file and close the 
    # program with error code 12. Also if the file removal fails I still want 
    # to exit with status code 12


    # Split the sorted list into 4 separate files

    # Create the list files
    touch "list1.txt"
    touch "list2.txt"
    touch "list3.txt"
    touch "list4.txt"

    remainder=0

    # Read the sorted_files.txt file line by line
    while IFS="" read -r line || [ -n "$line" ]; do
      # Calculate the remainder of the line counter divided by 4
      remainder=`expr \( $remainder + 1 \) % 4`

      # Distribute the line to the corresponding list file
      case $remainder in
        1)
          echo "$line" >> list1.txt
          ;;
        2)
          echo "$line" >> list2.txt
          ;;
        3)
          echo "$line" >> list3.txt
          ;;
        0)
          echo "$line" >> list4.txt
          ;;
      esac

    done < sorted_files.txt

    # Create 4 threads and assign each list to a thread
    convert_wav2mp3 list1.txt &
    convert_wav2mp3 list2.txt &
    convert_wav2mp3 list3.txt &
    convert_wav2mp3 list4.txt &

    # Wait for all threads to finish
    wait

    # Clean up temporary files
    cleanup 0
}


trap 'cleanup 1' INT # for sigint

# Check if the folder parameter is not provided
if test -z "$1"; then
	help
fi

while test "x$1" != "x"; do
	case "$1" in

	-h | --help) # The user is asking for helpppp
    if test "x$textOnly" = "xy"; then
      change "$1"
    else
        help
    fi
		;;
  --) # The user il telling us stop flags, from now on only text

		if test "x$textOnly" = "xy"; then
			change "$1"
		else
			textOnly=y
		fi

		;;

	-*) # The user just gave us either some text or an invalid flag

		if test "x$textOnly" = "xy"; then
			change "$1"
		else

      error_msg "Bad flag $1. Please refer to the help section with -h or --help"
      exit 10
			
		fi
		;;

	*) # Hopefully a valid name for the directory

		change "$1"

		;;

    esac
    shift
done

