#!/bin/bash

## Place this script into root folder that contains .7z archives
## May need to chmod +x file to make executable

## Uncomment below if required software not on system
#sudo apt-get install -y mame-tools p7zip-full

## Extract 7z
for x7zFile in *.7z; do
  gameName="$(basename "$x7zFile" .7z)"
  printf "\n>> Extracting %s\n" "${gameName}"
  7z x "${x7zFile}" -o./"${gameName}-tmp"

  ## Convet to chd
  printf "\n>> Converting %s\n" "${gameName}"
  if [ -f "./${gameName}-tmp/${gameName}.cue" ]; then
    chdman createcd -i "./${gameName}-tmp/${gameName}.cue" -o ./"${gameName}.chd"
  else
    if [ -f "./${gameName}-tmp/${gameName}.iso" ]; then
      chdman createcd -i "./${gameName}-tmp/${gameName}.iso" -o ./"${gameName}.chd"
    fi
  fi

  ## Delete temporary directory
  rm -R ./"${gameName}-tmp"

  ## Delete original 7z archive
  if [ -f ./"${gameName}.chd" ]; then
    rm ./"$x7zFile"
    printf "\n>> %s complete\n" "${gameName}"
  else
    printf "\n>> %s failed\n" "${gameName}"
  fi

done

printf "\nAll done."
