#!/bin/bash

aRequiredDirs=(data nwm)
aRequiredFiles=(chitin.key dialog.tlk nwserver)
aLCDirs=(ambient data dmvault hak localvault music override portraits)
aProblemFiles=()
aWritables=(nwn.ini nwnplayer.ini nwncdkey.ini saves localvault tempclient currentgame dmvault)

printf "Checking for required files\n\n"

for d in ${aRequiredDirs[@]}
do
    if [ -d $d ]
    then
        printf "PASSED: $d directory exists\n"
    else
        printf "FAILED: $d directory missing\n"
        exit
    fi
done

if [ -f dialog.TLK ]
then
    mv dialog.TLK dialog.tlk
fi

for f in ${aRequiredFiles[@]}
do
    if [ -f $f ]
    then
        printf "PASSED: $f exists\n"
    else
        printf "FAILED: $f missing\n"
        exit
    fi
done

printf "\nFixing case\n\n"

if [ -f dialogF.TLK ]
then
    mv dialogF.TLK dialogf.tlk
fi

if [ -f texturepacks/xp2_gui.erf ]
then
    mv texturepacks/xp2_gui.erf texturepacks/XP2_GUI.erf
fi

for d in ${aLCDirs[@]}
do
    if [ -d $d ]
    then
        printf "$d\n"
  
        cd $d

        for f in $(find . -name '*.*')
        do
            lcf=$(echo $f | tr [:upper:] [:lower:])
            if [ $f != $lcf ]
            then
	        if [ -f $f ]
	        then
	            mv $f $(echo $f | tr [:upper:] [:lower:]) 
	        fi
            fi
            printf .
        done

        cd ..

        printf "\n"
    fi
done

defIFS=$IFS
IFS='|'

if [ -d saves ]
then
    cd saves
    for d in $(find . -name '* - *' -type d -printf "%f|")
    do
        printf "saves/$d\n"

        cd "$d"

        if [ -f Portrait.tga ]
 	then
 	    mv Portrait.tga portrait.tga
 	fi

 	if [ -f Screen.tga ]
 	then
 	    mv Screen.tga screen.tga
 	fi
	
	cd ..
    done
    cd ..
fi

IFS=$defIFS

printf "\nChecking for problem files\n\n"

for f in ${aProblemFiles[@]}
do
    if [ -e $f ]
    then
        printf "WARNING: $f exists, deleting this file is recommended\n"
    fi
done

printf "\nChecking for permissions\n\n"

for f in ${aWritables[@]}
do
    if [ -e $f ]
    then
        if [ -w $f ]
        then
            printf "PASSED: $f is writable\n"
        else
            printf "WARNING: $f is not writable\n"
        fi
    fi
done

if [ -w $(pwd) ]
then
   printf "PASSED: $(pwd) is writable\n"
else
   printf "WARNING: $(pwd) is not writable\n"
fi

printf "\nYou are ready to run Neverwinter Nights.\n\n"
