#!/bin/bash
PROGNAME="$(basename "$0")"

TEMP=$(getopt -o 'hA::S:' -l 'help,anim::,seed:' -n "$PROGNAME" -- "$@")
if [ $? -ne 0 ]; then
	echo 'Terminating...' >&2
	exit 1
fi
eval set -- "$TEMP"
unset TEMP

DEFAULT_SEED=$[$(date +%N) % 0x1000000]
DEFAULT_ANIM=no
DEFAULT_NUMPICS=36

SEED=$DEFAULT_SEED
ANIM=$DEFAULT_ANIM
NUMPICS=$DEFAULT_NUMPICS

while true; do
	case "$1" in
		'-h'|'--help')
		  echo >&2 'usage: '"$PROGNAME"' [options...][--][povray options...]

options:
  -h, --help                print this help, and exit nicely.

  -S num, --seed=num        set random number generator start seed. ['$DEFAULT_SEED']
  -A [num], --anim[=num]    set anim mode ['$DEFAULT_ANIM']
                            (optional) set number of frames in anim ['$DEFAULT_NUMPICS']
'
      shift
      exit 0
    ;;

    '-A'|'--anim')
      ANIM=yes
      echo -n 'Anim mode set'
      if [ -z "$2" ]; then
        echo
      else
        let NUMPICS=$2 || exit 1
        echo ' with '$NUMPICS' pics'
      fi
      shift 2
		  continue
		;;

		'-S'|'--seed')
		  let SEED=$2 || exit 1
		  echo 'SEED set to '$SEED
		  shift 2
		  continue
		;;

		'--')
			shift
			break
		;;

		*)
			echo 'Internal error!' >&2
			exit 1
		;;
	esac
done

echo '#declare SEED = '$SEED';' >seed.inc

if [ "$ANIM" == no ]; then
  povray scene.ini "$@" +d +p -c
else
  mkdir -p pics
  #rm -f pics/*
  LEN=${#NUMPICS}
  FMT='pics/i%0'$LEN'd.png'
  povray scene.ini -d "$@" +opics/i.png +kfi1 +kff$NUMPICS +ki0.0 +kf1.0 +kc &&
    ffmpeg &>ffmpeg.log -nostdin -r 10 -f image2 -i "$FMT" -c:v gif -y "$SEED.gif" &&
      rm -f ffmpeg.log
fi

