#!/bin/bash

# Need byzanz

# use as :
# ./recordToGif.sh 60 -c /path/to/file.gif
# where 60 is 60 seconds
# where -c is grab cursor
# select the window to record...


# Delay before starting
DELAY=3

# Sound notification to let one know when recording is about to start (and ends)
beep() {
    /usr/bin/beep
}

# Duration and output file
if [ $# -gt 0 ]; then
    D="--duration=$@"
else
    echo use as ./recordToGif.sh 60 -c /path/to/file.gif
    echo where -c is show cursor
    echo where 60 are 60 seconds
    echo select the window to record...
    beep
    exit
fi

XWININFO=$(xwininfo)

X=`awk -F: '/Absolute upper-left X/{print $2}' <<< "$XWININFO"`
Y=`awk -F: '/Absolute upper-left Y/{print $2}' <<< "$XWININFO"`
W=`awk -F: '/Width/{print $2}' <<< "$XWININFO"`
H=`awk -F: '/Height/{print $2}' <<< "$XWININFO"`

echo Delaying $DELAY seconds. After that, byzanz will start

for (( i=$DELAY; i>0; --i )) ; do
    echo $i
    sleep 1
done

echo ":::::::::::::::::::::::::::::::::::::::::::::::::::::::"
beep
byzanz-record --verbose --delay=0 -x $X -y $Y -w $W -h $H $D & read FULLDURATION FAKE <<<$(IFS=";"; echo $D)
read FAKE DURATION <<<$(IFS="="; echo $FULLDURATION)

for (( i=$DURATION; i>0; --i )) ; do
    if [ $i -ne $DURATION ]; then
        echo $i seconds
    fi
    sleep 1
done
beep
