#!/bin/bash

####################################################################
#
# Script to invoke the simulator with a constrained (5 MB) drmdump
# directory mounted at the location pointed to by <DUMP_DIR>.
# This option is useful to evaluate how resilient drm dump generation code
# is to out-of-disk space errors.
#
# XXX - When invoked this script may trigger a few exceptions in drmsuite.py.
# These exceptions seem unrelated to dummyVpxd's ability to handle out-of-space
# dump directory, but need to get to the root of this.
#
####################################################################
OSNAME=`uname -s`
SCRIPT="$0"

BUILD="obj"
DEFAULT_PYTHON="python-2.6.1"
PYTHON=/build/toolchain/lin32/${DEFAULT_PYTHON}/bin/python

DUMPDIR="/mnt/vfs"
DUMPFILE="/tmp/vfs"
LOOP="/dev/loop0"

function setupDumpDir {
    dd if=/dev/zero of=$DUMPFILE bs=4096 count=5120
    sudo losetup $LOOP $DUMPFILE
    sudo mkfs -t ext3 -m 1 -v $LOOP
    sudo mkdir $1
    sudo mount $LOOP $1
    sudo chmod 777 $1
}

function tearDownDumpDir {
    sudo umount $1
    sudo losetup -d $LOOP
    sudo rmdir $1
    rm $DUMPFILE
}

while getopts "c" OPTION
do
   case $OPTION in
      c)
         echo "Compiling DRM apps ... "
         cd ..
         scons BUILDTYPE=${BUILD} PRODUCT=vpx drm-apps
         cd bora
         ;;
   esac
done

case "${OSNAME}" in
    Linux )
        PYTHON=/build/toolchain/lin32/${DEFAULT_PYTHON}/bin/python
        ;;
    CYGWIN_NT-5.* | CYGWIN_NT-6.* )
        case "${TCROOT}" in
        "" )
           echo "TCROOT is not defined."
           exit 1
        esac
        TCROOT=`cygpath -w "${TCROOT}"`
        PYTHON="${TCROOT}/win32/${DEFAULT_PYTHON}/python.exe"
        ;;
    Darwin )
        PYTHON=/build/toolchain/mac32/${DEFAULT_PYTHON}/bin/python
        ;;
    * )
        echo "Unsupported os name (${OSNAME})."
        exit 1
        ;;
esac

USE_STRIPPED=true

if [ ! "${DRMAPPS}" ]; then
   DRMAPPS="${PWD}"/build/vpx/"${BUILD}"/drm-apps
   USE_STRIPPED=false
fi


if [ ! "${OUTDIR}" ]; then
   OUTDIR="${PWD}"/build/"${BUILD}"/vpx/drmtest
fi

if [ ! -d "$OUTDIR" ]; then
   mkdir -p "$OUTDIR"
fi

setupDumpDir $DUMPDIR

if [ ${USE_STRIPPED} = true ]; then
   SIM_BIN=${DRMAPPS}/bin/dummydrm
   REPLAY_BIN=${DRMAPPS}/bin/drmreplay
   APPS_LIBS=${DRMAPPS}/lib
else
   SIM_BIN=${PWD}/build/build/dummydrm/obj/linux64/dummydrm
   REPLAY_BIN=${PWD}/build/build/drmreplay/obj/linux64/drmreplay
   source ${DRMAPPS}/ldconfig
   APPS_LIBS=${DEBUG_LIBS}:${DRMAPPS}/lib
fi

LD_LIBRARY_PATH={APPS_LIBS} "${PYTHON}" "${DRMAPPS}"/python/drmsuite.py \
   -d ${SIM_BIN} --replay-bin ${REPLAY_BIN} -B "${DRMAPPS}"/tests \
   -o "${OUTDIR}" -M "${DUMPDIR}" "$@"

tearDownDumpDir $DUMPDIR
