#!/bin/sh

if pkg-config gtk+-2.0; then
echo -e "\nGTK 2.0 and pkg-config exist. Compiling for GTK."
USEGTK="-DTUNE_GTK_INTERFACE=1 "
PKGOPTS=`pkg-config gtk+-2.0 --cflags --libs`
echo -e "Looking for various pieces of software."
if which konsole; then
PLAYERSHELL='"'`which konsole`'", "-e", '
elif which gnome-terminal; then
PLAYERSHELL='"'`which gnome-terminal`'", "-x", '
fi
if which timidity; then
OURPLAYER='"'`which timidity`'", "-A", "100"'
if [ -z "$PLAYERSHELL" ]; then
MIDIPLAYERSYNCH="-DTUNE_PLAY_SYNCH=1 "
else
MIDIPLAYERSYNCH="-DTUNE_PLAY_SYNCH=0 "
fi
elif which kmidi; then
OURPLAYER='"'`which kmidi`'"'
MIDIPLAYERSYNCH="-DTUNE_PLAY_SYNCH=0 "
fi
if which a2ps; then
OURPRINTER='"'`which a2ps`'", "--margin", "-T", "4"'
FILEPRINTSYNCH="-DTUNE_PRINT_SYNCH=1 "
elif which kprinter; then
OURPRINTER='"'`which kprinter`'"'
FILEPRINTSYNCH="-DTUNE_PRINT_SYNCH=0 "
elif which lp; then
OURPRINTER='"'`which lp`'"'
FILEPRINTSYNCH="-DTUNE_PRINT_SYNCH=1 "
fi

if [ -z "$OURPLAYER" ]; then
echo -e "No MIDI file player will be specified."
else
MIDIPLAYER=${MIDIPLAYERSYNCH}"-D'TUNE_MIDI_PLAYER="${PLAYERSHELL}${OURPLAYER}"' "
fi

if [ -z "$OURPRINTER" ]; then
echo -e "No Tune file printer will be specified."
else
FILEPRINTER=${FILEPRINTSYNCH}"-D'TUNE_FILE_PRINTER="${OURPRINTER}"' "
fi

else

echo -e "\nCompiling for the standard command-line interface."
USEGTK="-DTUNE_GTK_INTERFACE=0 "
if [ -f /usr/include/unistd.h ] && [ -f /usr/include/sys/stat.h ]; then
echo -e "The POSIX stat function is available. Its use will give us better error messages."
STATOPT="-DGOT_STAT=1 "
fi

fi

TUNEOPTIONS=${USEGTK}${MIDIPLAYER}${FILEPRINTER}${STATOPT}"-lc "${PKGOPTS}

echo -e "cc TuneToMidi.c \c" > BuildTuneToMidiX
echo -e "${TUNEOPTIONS}\c" >> BuildTuneToMidiX
echo " -O -o TuneToMidi" >> BuildTuneToMidiX

chmod 700 BuildTuneToMidiX

echo -e "\nExecuting the build command\n"
cat BuildTuneToMidiX
echo -e ""

if ./BuildTuneToMidiX; then
DID_IT=1
else
DID_IT=0
fi

rm BuildTuneToMidiX

#Did it compile?

if [ ${DID_IT} == 1 ]; then
chmod 700 TuneToMidi
echo -e "TuneToMidi was successfully created!\n"
else
echo -e "TuneToMidi was NOT created."
echo -e "Something went wrong; check the error messages above.\n"
fi
