#!/bin/bash

if [ "$1" == "--help" ]
then
   echo "With no commands, it will download the sheep in the file named latest"
   echo "With one argument, a number, it will download and render that sheep."
   echo "www.aaronash.com - www.andrewash.com"
   exit
fi

export WIDTH=1680
export HEIGHT=1050
export QUALITY=15000

while [ 1 ]
do

	if [ -n "$1" ]
	then
	    export SHEEP=$1
        $1 = ""
	else
	    export SHEEP=`cat latest`
	fi

	export FLAM3=$SHEEP.flam3 

	echo "Downloading sheep $SHEEP..."

	wget -nc --progress=bar http://sheepserver.net/v2d6/gen/202/$SHEEP/spex
	mv spex genomes/$FLAM3

	if [ ! -e genomes/$FLAM3 ]
	then
	    echo "Failed in download sheep...  abort"
	fi

	# ditch all but first flame
	sed -i "" genomes/$FLAM3

	sed -i "s/size=\"[0-9]* [0-9]*\"/size=\"$WIDTH $HEIGHT\"/g" genomes/$FLAM3	# fix size
	sed -i "s/quality=\"[0-9]*\"/quality=\"$QUALITY\"/g" genomes/$FLAM3   		# fix quality

	echo "Rendering sheep $SHEEP..."
	env time=0 flam3-render < genomes/$FLAM3
	mv 00000.png pngs/0$SHEEP-$WIDTH-$HEIGHT.png
	echo "Done rendering sheep $SHEEP."

	echo "$SHEEP+1" | bc > latest

    echo "Creating thumbnail of sheep $SHEEP..."
	convert -scale 200x200 pngs/0$SHEEP-$WIDTH-$HEIGHT.png thumb/th-0$SHEEP-$WIDTH-$HEIGHT.jpg

	#ftp enteryourwebsitenamehere.com 21 user enteryourusernamehere enteryourftppasswordhere
    echo "Uploading original and thumbnail to enteryourwebsitenamehere.com..."
	echo "hash
	put pngs/0$SHEEP-$WIDTH-$HEIGHT.png pngs/0$SHEEP-$WIDTH-$HEIGHT.png
	put thumb/th-0$SHEEP-$WIDTH-$HEIGHT.jpg thumb/th-0$SHEEP-$WIDTH-$HEIGHT.jpg" | ftp enteryourwebsitenamehere.com 21
    echo "Done uploading."

done
