#!/bin/bash
VERSION=0.1
_maketemp(){
    mktemp -q "/tmp/$(basename "${0}").XXXXXX"
    if [ "${?}" -ne 0 ]; then
        echo "${0}: Can't create temp file, exiting..."
        _writeerrorlog "_maketemp" "was unable to create the temp file, so the script had to exit."
        exit 1
    fi
}
_usage(){
    echo
    echo "$(basename "${0}") ${VERSION}"
    echo "This script is to test MediaConch policies in prototyping. This script is intended to be deprecated by MediaConch itself."
    echo "Usage: $(basename "${0}") [ -c optional_file_to_compare_to.mkv ] [ -p policy.xml ] [ -d display_type ] av_file_to_test_1 [ av_file_to_test_2 ...]"
    echo "  -c (specify a file to compare the inputs to)"
    echo "  -p (specify a policy)"
    echo "  -d (specify a display xsl)"
    echo "  -h ( display this help )"
    echo
    exit
}
[ "${#}" = 0 ] && _usage

OPTIND=1
while getopts ":c:p:d:h" OPT ; do
    case "${OPT}" in
        c) comparefile="${OPTARG}";;
        p) policyfile="${OPTARG}";;
        d) displayfile="${OPTARG}";;
        h) _usage ;;
        *) echo "bad option -${OPTARG}" ; _usage ;;
        :) echo "Option -${OPTARG} requires an argument" ;;
    esac
done
shift $(( ${OPTIND} - 1 ))

if [ ! -f "${policyfile}" ] ; then
  echo "Error: ${policyfile} is not a file."
  exit
fi

if [ -f "${comparefile}" ] ; then
  compare_tmp=$(_maketemp)
  mediaconch -mi -mmt -fx --force "${comparefile}" > "${compare_tmp}"
else
  if [ "${comparefile}" ] ; then
    echo "Error: ${comparefile} is not a file."
  fi
fi

while [ "${*}" != "" ] ; do
  INPUT="${1}"
  shift
  mc_tmp=$(_maketemp)
  mediaconch -mi -mmt -fx --ParseSpeed=0.5 --force "${INPUT}" > "${mc_tmp}"
  if [ -f "${displayfile}" ] ; then
    xsltproc ../policyset2policytransform2policyresult.xsl "${policyfile}" | sed 's/aliasxsl/xsl/g' | sed 's|xmlns:xsl="my:namespace"|xmlns:xsl="http://www.w3.org/1999/XSL/Transform"|g' | xsltproc - "${mc_tmp}" | xsltproc "${displayfile}" -
  elif [ -f "${compare_tmp}" ] ; then
    xsltproc --stringparam compare "${compare_tmp}" ../policyset2policytransform2policyresult.xsl "${policyfile}" | sed 's/aliasxsl/xsl/g' | sed 's|xmlns:xsl="my:namespace"|xmlns:xsl="http://www.w3.org/1999/XSL/Transform"|g' | xsltproc - "${mc_tmp}"
  else
    xsltproc ../policyset2policytransform2policyresult.xsl "${policyfile}" | sed 's/aliasxsl/xsl/g' | sed 's|xmlns:xsl="my:namespace"|xmlns:xsl="http://www.w3.org/1999/XSL/Transform"|g' | xsltproc - "${mc_tmp}"
  fi
done