#!/bin/sh
if [ ! -f NetServer.exe ]
then echo 'File NetServer.exe not found in this directory. Exiting.'; exit
fi
netserver_size=`cat NetServer.exe|wc -c`
export netserver_size
echo 'Size of file to patch is:' $netserver_size
if [ $netserver_size -eq 122880 ]
then echo 'Good...'
else echo 'Wrong NetServer.exe, not 122880 bytes in size (is it v1.03?). Exiting.'; exit
fi
if [ ! -f upload.hex ]
then echo 'File upload.hex not found in this directory. Exiting.'; exit
fi
upload_size=`cat upload.hex|wc -c`
export upload_size
echo 'Size of file to insert is:' $upload_size
if [ $upload_size -le 40342 ]
then echo 'Good...'
else echo 'Hexfile to upload >40342 bytes, sorry. Exiting.'; exit
fi
echo '==============================================='
echo 'Pre-checks ok, seems to be v1.03, now patching...'
echo '==============================================='
echo 'Splitting EXE file...'
head -c 40356 NetServer.exe > NetServer_head.exe
tail -c 42182 NetServer.exe > NetServer_tail.exe
echo 'Create empty file (be patient, may take quite some time at the first run...)'
touch empty.hex
empty_size=`cat empty.hex|wc -c`
export empty_size
while [ $empty_size -lt 40342 ]
do echo '                                ' >> empty.hex; empty_size=`cat empty.hex|wc -c`
done
echo 'Tailoring HEX file...'
filler_size=`echo 40342 - $upload_size | bc` 
export filler_size
head -c $filler_size empty.hex > filler.hex
echo 'Creating new NetServer_Patched.exe...'
cat NetServer_head.exe upload.hex filler.hex NetServer_tail.exe > NetServer_Patched.exe
echo '==============================================='
echo 'Checking again...'
echo '==============================================='
rm -rf NetServer_head.exe NetServer_tail.exe filler.hex
new_size=`cat NetServer_Patched.exe|wc -c`
export new_size
if [ $new_size -eq 122880 ]
then echo 'Good...'
else echo 'Wrong result, not 122880 bytes in size. Exiting.'; rm -f NetServer_Patched.exe; exit
fi
echo 'Done. Now start the new tool NetServer_Patched.exe and '
echo 'use the firmware upload feature to program upload.hex!'
echo 'You may use NetServer.exe to upload the regular version again!'