#!/bin/bash

# ==== Utility functions ====

escape()
{
echo "$1"| sed -e "s/ /\\\\\\ /g"
}

abspath(){
	readlink -m "$1"
}

renderscript(){
	[ -d "`dirname "$RENDERSCRIPT"`" ] || mkdir -p "`dirname "$RENDERSCRIPT"`"
	if [ -z $UPDATE ]; then
		UPDATE=0
	fi
	cat > "$RENDERSCRIPT" << EOF
import sys

try:
	import Blender
	blender_version = "2.4x"
except:
	import bpy
	blender_version = "2.5x"
	

def main():
	update = $UPDATE
	if blender_version == "2.4x":
		# Blender 2.4x
		for sce in Blender.Scene.Get():
			rend = sce.render
			rend.freeImages = True
			rend.saveBuffers = True
			rend.compositeFree = True
	
			#rend.oversampling = $OSA
	
			#rend.OSALevel = 8
	
			rend.fieldRendering = False
	
			if sce.getName() == 'Scene':
				sce.makeCurrent()
	
		# Scene rendering setting
		sce = Blender.Scene.GetCurrent()
		
		for ob in sce.objects:
			if ob.name=="$CAMERA":
				sce.setCurrentCamera(ob)
				break
		
		rend = sce.render

		rend.renderwinSize = 100

		#rend.enablePremultiply()

		#rend.enableRGBAColor()

		# Suff for updating file
		size_x = rend.sizeX
		size_y = rend.sizeY
		fps = rend.fps
EOF
	# Get image dimensions from file if it's unspecified


	[ -z $WIDTH ] || echo "		rend.sizeX = $WIDTH" >> "$RENDERSCRIPT"
	[ -z $HEIGHT ] || echo "		rend.sizeY = $HEIGHT" >> "$RENDERSCRIPT"
	
	cat >> "$RENDERSCRIPT" << EOF

		rend.xParts = 4
		rend.yParts = 4

		rend.fps = $FPS

		# OPENEXR stuff
		#rend.zbuf = False
		#rend.halfFloat = True
		#rend.preview = False

		rend.touch = False
		rend.noOverwrite = False

		# rend.imageType = Blender.Scene.Render.$BLENDERFORMAT

		# Update .blend file if we have width or height changed
		if update != 0 and ( size_x != rend.sizeX or size_y != rend.sizeY or fps != rend.fps ):
			Blender.Save("`pwd`/$TARGET", 1)
	else:
		# Blender 2.5x
		for sce in bpy.data.scenes:
			rend = sce.render
			#rend.use_free_image_textures = True		# not in 2.53 yet
			#rend.use_save_buffers = True				# not in 2.53 yet
			#rend.use_free_unused_nodes = True			# not in 2.53 yet
			
			#rend.use_antialiasing = $OSA				# not in 2.53 yet
	
			#rend.antialiasing_samples = '8'
	
			#rend.use_fields = False					# not in 2.53 yet
		
		# Settings below should apply for current scene
		sce = bpy.context.scene
		
		for ob in sce.objects:
			if ob.name=="$CAMERA":
				sce.camera=ob
				break
		
		rend = sce.render

		rend.resolution_percentage = 100

		#rend.alpha_mode = "PREMUL"

		#rend.color_mode = "RGBA"

		# Suff for updating file
		size_x = rend.resolution_x
		size_y = rend.resolution_y
		fps = rend.fps
EOF
	# Get image dimensions from file if it's unspecified


	[ -z $WIDTH ] || echo 	"		rend.resolution_x = $WIDTH" >> "$RENDERSCRIPT"
	[ -z $HEIGHT ] || echo	"		rend.resolution_y = $HEIGHT" >> "$RENDERSCRIPT"

	cat >> "$RENDERSCRIPT" << EOF

		rend.parts_x = 4
		rend.parts_y = 4

		rend.fps = $FPS

		# OPENEXR stuff
		#rend.exr_zbuf = False
		#rend.use_exr_half = True
		#rend.exr_preview = False

		rend.use_placeholder = False
		rend.use_overwrite = True

		# rend.file_format = $BLENDERFORMAT

		# Update .blend file if we have width or height changed
		if update != 0 and ( size_x != rend.resolution_x or size_y != rend.resolution_y or fps != rend.fps ):
			bpy.ops.wm.save_mainfile("EXEC_DEFAULT",filepath="`pwd`/$TARGET")


	
if __name__ == '__main__':
	main()
EOF
}

info_blender_path(){
	cat << EOF
          If you installing tar.bz2 package from the 
          official website, make sure that correct Blender 
          binary is available via your system path so it can
          be found by Remake. To achieve that you may need 
          to invoke command like this before running Remake:

           $ export PATH=/path/to/your/blender/installation:\$PATH

EOF
}

info_blender_get(){
	if [[ ${BLENDER_VERSION:0:3} == '2.4' ]]; then
		info_blender_get24
	elif [[ ${BLENDER_VERSION:0:3} == '2.5' ]]; then
		info_blender_get25
	elif [[ ${BLENDER_VERSION:0:3} == '2.6' ]]; then
		info_blender_get26
	else
	cat << EOF
          You can get prebuilt Blender packages from the following 
          sources:
            * http://www.blender.org/download/get-blender/
            * http://download.tuxfamily.org/morevna/morevnapackage/binaries/blender/

EOF
	fi
}

info_blender_get24(){
	cat << EOF
          You can get prebuilt Blender packages from the following 
          sources:
            * http://download.blender.org/release/
            * http://download.tuxfamily.org/morevna/morevnapackage/binaries/blender/

EOF
}
info_blender_get25(){
	cat << EOF
          You can get prebuilt Blender packages from the following 
          source:
            * http://download.blender.org/release/

EOF
}
info_blender_get26(){
	cat << EOF
          You can get prebuilt Blender packages from the following 
          source:
            * http://www.blender.org/download/get-blender/
            * http://download.tuxfamily.org/morevna/morevnapackage/binaries/blender/

EOF
}

# ==== Module functions ====

format(){
	echo $FORMAT
}

check(){
	# Re-reading config to get BLENDER_VERSION if available
	. "$PROJECTROOT/remake.conf"
	
	# Check for Blender binary
	if ! ( which blender > /dev/null 2>&1 ); then
		echo "   FATAL: Can't find 'blender' binary!" >&2
		echo
		if [ ! -z "$BLENDER_VERSION" ]; then
			echo "          This project requires Blender ${BLENDER_VERSION:0:3}x."
		fi
		info_blender_get
		info_blender_path
		exit 1
	fi
	echo "   Blender binary found: `which blender`"
	
	# Check for Blender version
	BLENDER_VERSION_FOUND=`blender --version`
	BLENDER_VERSION_FOUND=${BLENDER_VERSION_FOUND:8:4}
	export BLENDER_VERSION_FOUND
	echo "   Blender version: $BLENDER_VERSION_FOUND"
	
	# Check if we have preferred version for the project
	if [ ! -z "$BLENDER_VERSION" ]; then
		# Get rid of "x" in 2.4x form
		BLENDER_VERSION=${BLENDER_VERSION%x*}
		BLENDER_VERSION=${BLENDER_VERSION:0:4}
		if [[ `echo $BLENDER_VERSION | wc -m ` == 4 ]]; then
			BLENDER_VERSION_FOUND=${BLENDER_VERSION_FOUND:0:3}
		fi
		
		if [[ "${BLENDER_VERSION_FOUND}" != "${BLENDER_VERSION}" ]]; then
			echo
			cat << EOF
   ERROR: This project requires Blender ${BLENDER_VERSION}.
          Please install appropriate version of Blender.

EOF
			info_blender_get
			info_blender_path
			cat <<EOF
          If you still want to use different version of Blender, you 
          should edit value of BLENDER_VERSION variable in remake.conf
          file of your project.
          
EOF
			exit 1
		fi
	else # [ -z "$BLENDER_VERSION" ]
		echo "BLENDER_VERSION=${BLENDER_VERSION_FOUND}" >> "$PROJECTROOT/remake.conf"
	fi
	
	# Check for FFMPEG support compiled in
	OSA="True"
	BLENDERFORMAT="MPEG"
	UPDATE=0 # This is critical!
	RENDERSCRIPT="${PROJECTROOT}/render/tmp/mod_blend_check.py"
	OUTPUT="${PROJECTROOT}/render/tmp/mod_blend_check.mpg"
	renderscript
	RANGE="-a"
	( blender -b "$TESTDATA_PATH/blender-ffmpeg-and-audio-hd.blend" -S Scene -P "$RENDERSCRIPT" -o "$OUTPUT" -x 1 -F $BLENDERFORMAT -t 0 $RANGE 2>&1 | grep -E '^Saved: ' ) || true
	if [ ! -f "$OUTPUT" ]; then
		echo
		cat << EOF
   FATAL: Installed version of Blender have no FFMPEG 
          support! Please install Blender version compiled 
          with that feature enabled.

EOF
		info_blender_get
		info_blender_path
		exit 1
	fi
	rm -f "$OUTPUT"
	
	
	# Check for Audio RAM dependency bug
	DEPS=`deps "$TESTDATA_PATH/blender-ffmpeg-and-audio-hd.blend" | egrep "test.wav" || true`
	if [ -z "$DEPS" ]; then
		echo "   Audio RAM bug: Yes"
		echo
		cat << EOF
   WARNING! You are using Blender 2.4x which have an important bug - 
            if your blend file have audio file imported as "Audio HD",
            then it will not be detected as dependency. Be aware that
            this can lead to some problems. For example, if you use 
            'pack' function of Remake, those files will not be 
            included into pack and you have to add them to archive 
            manually.
EOF
		echo
		sleep 1
	else
		echo "   Audio RAM bug: No"
	fi
	
	# git stuff
	( cat "$PROJECTROOT/.gitignore" | egrep "\*.blend1" > /dev/null ) || ( echo "*.blend1" >> "$PROJECTROOT/.gitignore" )
}

deps(){
	if [ ! -z "$1" ]; then 
		TARGET=$1
	fi
	
	SCRIPTPATH="$(abspath "${0}")_deps"
	
	blender -b "`abspath \"$TARGET\"`" -P "$SCRIPTPATH" 2>&1 | grep -E "^dependency: " | sed -e 's/^dependency: //'
}

rules(){
	OSA="True"
	
	BLENDERFORMAT=`echo $FORMAT | tr '[:lower:]' '[:upper:]'`
	if [[ $BLENDERFORMAT == 'MPG' ]]; then
		BLENDERFORMAT="MPEG"
	fi
	
	RENDERSCRIPT="`echo "$RENDERPATH" | sed -e "s|\.$FORMAT$|.py|"`"
	renderscript

	if [ ! -z $SINGLE ]; then
		RANGE="-f $SINGLE"
		OUTPUT="\`pwd\`/${RENDERPATH}-######"
		echo "`escape "$RENDERPATH"`: `escape "$TARGET"` $DEPS" >> "$MAKEFILE"
		echo "	rm -rf \"$RENDERPATH\"" >> "$MAKEFILE"
		echo "	blender -b \"\`pwd\`/$TARGET\" -S Scene -P \"\`pwd\`/$RENDERSCRIPT\" -o \"$OUTPUT\" -x 0 -F $BLENDERFORMAT -t $OPT_THREADS $RANGE 2>&1 | grep -E '^Saved: '" >> "$MAKEFILE"
		echo "	mv \"${RENDERPATH}-`printf %06d $SINGLE`\" \"$RENDERPATH\"" >> "$MAKEFILE"
	else
		if [ ! -z $FROM ]; then
			FROM=" -s $FROM "
		fi
		if [ ! -z $TO ]; then
			TO=" -e $TO "
		fi
		RANGE="-a"
		if [[ $BLENDERFORMAT == 'PNG' ]]; then
			OUTPUT="\`pwd\`/$RENDERPATH/file.####"
			echo "`escape "$RENDERPATH"`: `escape "$RENDERPATH/file.lst"`" >> "$MAKEFILE"
			echo "	touch \"$RENDERPATH\"" >> "$MAKEFILE"
			echo "`escape "$RENDERPATH/file.lst"`: `escape "$TARGET"` $DEPS" >> "$MAKEFILE"
		fi
		if [[ $BLENDERFORMAT == 'MPEG' ]]; then
			OUTPUT="\`pwd\`/$RENDERPATH"
			echo "`escape "$RENDERPATH"`: `escape "$TARGET"` $DEPS" >> "$MAKEFILE"
		fi
		echo "	rm -rf \"$RENDERPATH\"" >> "$MAKEFILE"
		if [[ $BLENDERFORMAT == 'PNG' ]]; then
			echo "	mkdir -p \"$RENDERPATH\"" >> "$MAKEFILE"
		fi
		echo "	blender -b \"\`pwd\`/$TARGET\" -S Scene -P \"\`pwd\`/$RENDERSCRIPT\" -o \"$OUTPUT\" -x 1 -F $BLENDERFORMAT -t $OPT_THREADS $FROM $TO $RANGE 2>&1" >> "$MAKEFILE"
		if [[ $BLENDERFORMAT == 'PNG' ]]; then
			echo "	echo \"FPS $FPS\" > \"$RENDERPATH/file.lst\"" >> "$MAKEFILE"
			echo "	( cd \"$RENDERPATH\"; ls -1 *.$FORMAT >> file.lst )" >> "$MAKEFILE"
		fi
	fi

	echo "`escape "$RENDERPATH-clean:"`" >> "$MAKEFILE"
	echo "	rm -rf \"$RENDERPATH\"" >> "$MAKEFILE"
	echo "	rm -rf \"$RENDERSCRIPT\"" >> "$MAKEFILE"
}

$1 "$2"
