#! /bin/sh
#
# Sets up the Qtetris package for building with the specified compiler,
# and if possible converting text files to the desired target format.
# Based in `fix.sh' of the Allegro library.

proc_help()
{
   echo
   echo "Usage: ./fix.sh <platform> [--quick|--dtou|--utod|--utom|--mtou]"
   echo
   echo "Where platform is one of: bcc32, beos, djgpp, mingw32, msvc, qnx, rsxnt, unix"
   echo "mac and watcom."
   echo "The --quick parameter turns of text file conversion, --dtou converts from"
   echo "DOS/Win32 format to Unix, --utod converts from Unix to DOS/Win32 format,"
   echo "--utom converts from Unix to Macintosh format and --mtou converts from"
   echo "Macintosh to Unix format. If no parameter is specified --dtou is assumed."
   echo

   NOCONV="1"
}

proc_fix()
{
   echo "Configuring Qtetris..."

   if [ "$1" != "none" ]; then
      echo "# generated by fix.sh" > makefile
      echo "MAKEFILE_INC = $1" >> makefile
      echo "include makefile.all" >> makefile
   fi
}

proc_filelist()
{
   echo "Converting Qtetris files..."

   FILELIST="`find . -type f "(" \
      -name "*.c" -o -name "*.h" -o -name "makefile.*" -o \
      -name "*.cfg" -o -name "*.txt" -o -name "*.arg" \
   ")"`"
}

proc_utod()
{
   proc_filelist
   for file in $FILELIST; do
      echo "$file"
      cp $file _tmpfile
      perl -p -i -e "s/([^\r]|^)\n/\1\r\n/" _tmpfile
      touch -r $file _tmpfile
      mv _tmpfile $file
   done
}

proc_dtou()
{
   proc_filelist
   for file in $FILELIST; do
      echo "$file"
      mv $file _tmpfile
      tr -d '\015' < _tmpfile > $file
      touch -r _tmpfile $file
      rm _tmpfile
   done
   chmod -f +x configure *.sh misc/*.sh misc/*.pl
}

proc_utom()
{
   proc_filelist
   for file in $FILELIST; do
      echo "$file"
      mv $file _tmpfile
      tr '\012' '\015' < _tmpfile > $file
      touch -r _tmpfile $file
      rm _tmpfile
   done
}

proc_mtou()
{
   proc_filelist
   for file in $FILELIST; do
      echo "$file"
      mv $file _tmpfile
      tr '\015' '\012' < _tmpfile > $file
      touch -r _tmpfile $file
      rm _tmpfile
   done
}

# prepare allegro for the given platform.

case "$1" in
   "bcc32"   ) proc_fix "makefile.bcc" ;;
   "beos"    ) proc_fix "makefile.be"  ;;
   "djgpp"   ) proc_fix "makefile.dj"  ;;
   "mingw32" ) proc_fix "makefile.mgw" ;;
   "msvc"    ) proc_fix "makefile.vc"  ;;
   "qnx"     ) proc_fix "makefile.qnx" ;;
   "rsxnt"   ) proc_fix "makefile.rsx" ;;
   "unix"    ) proc_fix "makefile.uni" ;;
   "mac"     ) proc_fix "makefile.mac" ;;
   "watcom"  ) proc_fix "makefile.wat" ;;
   "help"    ) proc_help;;
   *         ) proc_help;;
esac

# convert all text-file line endings.

cd ../
if [ "$NOCONV" != "1" ]; then
   case "$2" in
      "--utod"  ) proc_utod;;
      "--dtou"  ) proc_dtou;;
      "--utom"  ) proc_utom;;
      "--mtou"  ) proc_mtou;;
      "--quick" ) echo "No text file conversion...";;
      *         ) proc_dtou;;
   esac
fi
cd src/

echo "Done!"
