#!/bin/bash
set -eu

# Converts cardset images and config files in subdirs of the current
# directory from input-format to output-format (default: gif to bmp).
#
# Example to convert from gif format to png:
#
# $> cardconv gif png
#
# Needs package 'ImageMagick' being installed.

ifo='gif'
ofo='bmp'

if [ $# -eq 2 ]; then
  ifo=$1
  ofo=$2
elif [ $# -ne 0 ]; then
  echo "Usage: cardconv [INPUTFORMAT OUTPUTFORMAT]"
  echo "If formats are not specified, converts $ifo to $ofo."
  exit 1
fi

# Returns true if $1/config.txt exists and contains a mention of the input format
# file extension.
chkdir() {
  grep -qi "\.${ifo}" "${1}/config".txt
  return $?
}

# Usage: convdir in_dir out_dir
convdir() {
  mkdir -p "$2"

  # Convert all images
  if [ $ofo == 'png' ]; then
    for i in $1/*.$ifo; do
      convert "$i" "-matte" "-quality" "95" "png32:$2/$(basename $i .$ifo).$ofo"
    done
  else
    for i in $1/*.$ifo; do
      convert "$i" "$2/$(basename $i .$ifo).$ofo"
    done
  fi

  # Convert config.txt
  if [ -f $1/config.txt ]; then
    sed "s/\.${ifo}/.${ofo}/g" $1/config.txt > $2/config.txt
  fi
}

# Check all cardsets.
for in_dir in cardset-*; do
  out_dir=${in_dir}-${ofo}

  if [[ ! $in_dir =~ -$ofo$ ]] && [ ! -d $out_dir ] && chkdir $in_dir; then
    convdir $in_dir $out_dir
    echo "$out_dir created"
  fi
done
