#!/bin/bash
JAVA=java
SPIN=~/spin-6.5.1/spin.exe
# SPIN="$(cygpath -w ~/spin-6.4.7/spin.exe)"
# SPIN=spin
# declare -x UPPAAL_OLD_SYNTAX=1
VERIFYTA=~/uppaal-4.1.24/bin-Windows/verifyta.exe
GCC=gcc
TMP="/tmp"
BASE="$(cygpath -w ~/hugo-rt/dist)"
# CLASSES="$BASE\\bin"
LIB="$BASE\\lib"
# LIBS="$LIB\\*"
# CP="$CLASSES;$LIBS"
# HUGORT="$JAVA -ea -cp $CP control.Hugo"
HUGORT="$JAVA -jar $LIB\\hugort.jar"

MAXSEARCHDEPTH=10000

function translate2Promela {
  callHUGO="$HUGORT -opromela=$(cygpath -w $pmlname) ${additionalargs[@]} ${userargs[@]} $(cygpath -w $modelname)"
  msg="Translating model"
  echo "${msg}..."
  echo "${msg} ($callHUGO)..." >> ${logname}
  $callHUGO >${hugologname} 2>&1 ; statusHUGO=$? ; cat ${hugologname} >>${logname}
  grep "\[WARNING\]\|\[ERROR\]" ${hugologname}
  if [[ ${statusHUGO} != 0 ]]; then
    echo "Error while translating model \`$modelname', see transcript file"
    exit -1
  fi
}

function retranslate0Spin {
  pushd $TMP >/dev/null
  if [[ -r $pmlltlname ]]; then
    $SPIN -N "$(cygpath -w $pmlltlname)" -l -g -w -v -t "$(cygpath -w $pmlname)" >${tlname}
  else
    $SPIN -l -g -w -v -t "$(cygpath -w $pmlname)" >${tlname}
  fi
  popd >/dev/null

  callHUGO="$HUGORT -otrail=$(cygpath -w $utlname) ${additionalargs[@]} ${userargs[@]} $(cygpath -w $tlname) $(cygpath -w $modelname)"
  msg="Retranslating trace"
  echo "${msg}..."
  echo "${msg} ($callHUGO)..." >> ${logname}
  $callHUGO >${hugologname} 2>&1 ; statusHUGO=$? ; cat ${hugologname} >>${logname}
  grep "\[WARNING\]\|\[ERROR\]" ${hugologname}
  if [[ ${statusHUGO} != 0 ]]; then
    echo "Error while retranslating trace for \`$modelname', see transcript file"
    exit -1
  else
    echo "Wrote UML trail to $utlname" | tee -a ${logname}
  fi
}

function prepare4Spin {
  tmpname=${modelname%.*} # remove suffix (file name extension)
  tmpname=${tmpname##*/} # remove path
  pmlname=$TMP/${tmpname}.pml
  pmlltlname=$TMP/${tmpname}.pml.ltl
  ltlname=$TMP/${tmpname}.ltl
  tlname=$TMP/${tmpname}.tl
  utlname=$TMP/${tmpname}.utl
  logname=$TMP/${tmpname}.log
  hugologname=$TMP/${tmpname}.tmp.log
  rm -f $pmlname $pmlltlname $ltlname $tlname $utlname $logname $hugologname

  echo "Writing transcript to ${logname}..."
}

function executeSpin {
  pushd $TMP >/dev/null
  echo "${msg} ($callSPIN ; $callGCC ; $callPAN)..." >> ${logname}
  echo -n "${msg}: spin... "
  $callSPIN
  if [[ $? != 0 ]]; then
    echo "Error while verifying model \`$modelname', see transcript file"
    exit -1;
  fi
  echo -n "gcc... "
  $callGCC
  if [[ $? != 0 ]]; then
    echo "Error while verifying model \`$modelname', see transcript file"
    exit -1;
  fi
  echo -n "pan... "
  $callPAN >>$logname 2>&1
  if [[ $? != 0 ]]; then
    echo "Error while verifying model \`$modelname', see transcript file"
    exit -1;
  fi
  echo "done."
  popd >/dev/null
}

function check1Spin {
  prepare4Spin

  translate2Promela

  if grep "Observer() {" $pmlname >/dev/null; then
    callSPIN="$SPIN -a $(cygpath -m $pmlname)"
    callGCC="$GCC -O2 -DXUSAFE -DCOLLAPSE -o pan pan.c"
    callPAN="./pan -a -m$MAXSEARCHDEPTH"
    msg="Verifying model for interaction"
  elif [[ -r $pmlltlname ]]; then
    # Only keep non-empty lines not starting with a #
    grep -v "^$\|^#" $pmlltlname >$ltlname
    # Replace LTL formula with negated formula, since we are checking a never claim
    echo "!( $(cat $(cygpath -m $ltlname)) )" >$ltlname
    callLTL="$SPIN -F $(cygpath -m $ltlname)"
    echo >>$pmlltlname
    $callLTL >>$pmlltlname
    callSPIN="$SPIN -a -N $(cygpath -w $pmlltlname) $(cygpath -w $pmlname)"
    callGCC="$GCC -O2 -DVECTORSZ=32768 -DXUSAFE -DCOLLAPSE -o pan pan.c"
    callPAN="./pan -a -m$MAXSEARCHDEPTH"
    msg="Verifying model for LTL property"
  else
    callSPIN="$SPIN -a $(cygpath -m $pmlname)"
    callGCC="$GCC -O2 -DXUSAFE -DNOCLAIM -DSAFETY -DCOLLAPSE -o pan pan.c"
    callPAN="./pan -m$MAXSEARCHDEPTH"
    msg="Verifying model for assertion"
  fi

  executeSpin

  case "${msg}" in
    *interaction* )
      if grep "pan:1: acceptance cycle" $logname >/dev/null; then
        echo "A witness for the interaction has been found."
        retranslate0Spin
      else
        echo "NO witness for the interaction has been found."
        if grep "pan:1: assertion violated" $logname >/dev/null; then
          echo "But an assertion violation has been detected."
        fi
        if grep "pan:1: invalid end state" $logname > /dev/null; then
          echo "But an invalid end state has been detected."
        fi
        if grep "Warning: Search not completed" $logname > /dev/null; then
          echo "But the search has not been completed."
        fi
      fi
      ;;

    *LTL* )
      if grep "pan:1: assertion violated" $logname >/dev/null ||
         grep "pan:1: acceptance cycle" $logname >/dev/null; then
        echo "The property does NOT hold."
        retranslate0Spin
      else
        if grep "Warning: Search not completed" $logname > /dev/null; then
          echo "The search has not been completed."
        else
          echo "The property holds."
        fi
      fi
      ;;

    * )
      if grep "pan:1: assertion violated" $logname >/dev/null; then
        echo "Some assertion has been violated."
        retranslate0Spin
      elif grep "pan:1: invalid end state" $logname >/dev/null; then
        echo "A deadlock has been detected."
        retranslate0Spin
      elif grep "Warning: Search not completed" $logname > /dev/null; then
        echo "The search has not been completed."
      else
        echo "Nothing to report."
      fi
      ;;
  esac
}

function prepare4Uppaal {
  tmpname=${modelname%.*} # remove suffix (file name extension)
  tmpname=${tmpname##*/} # remove path
  taname=$TMP/${tmpname}.ta
  qname=$TMP/${tmpname}.q
  ltlname=$TMP/${tmpname}.ltl
  tlname=$TMP/${tmpname}.tl
  utlname=$TMP/${tmpname}.utl
  logname=$TMP/${tmpname}.log
  hugologname=$TMP/${tmpname}.tmp.log
  rm -f $taname $qname $ltlname $tlname $utlname $logname $hugologname

  echo "Writing transcript to ${logname}..."
}

function translate2TA {
  callHUGO="$HUGORT -ouppaal=$(cygpath -w $taname) ${additionalargs[@]} ${userargs[@]} $(cygpath -w $modelname)"
  msg="Translating model"
  echo "${msg}..."
  echo "${msg} ($callHUGO)..." >> ${logname}
  $callHUGO >${hugologname} 2>&1 ; statusHUGO=$? ; cat ${hugologname} >>${logname}
  grep "\[WARNING\]\|\[ERROR\]" ${hugologname}
  if [[ ${statusHUGO} != 0 ]]; then
    echo "Error while translating model \`$modelname', see transcript file"
    exit -1
  fi
}

function executeUppaal {
  callUPPAAL="$VERIFYTA -t 1 -s -q $(cygpath -w $taname) $(cygpath -w $qname)"
  msg="Verifying model"
  echo "${msg} ($callUPPAAL)..." >> ${logname}
  echo "${msg}... "
  $callUPPAAL 1>>${logname} 2>${tlname}
  if [[ $? != 0 ]]; then
    echo "Error while verifying model \`$modelname', see transcript file"
    exit -1;
  fi
}

function retranslate0Uppaal {
  callHUGO="$HUGORT -otrail=$(cygpath -w $utlname) ${additionalargs[@]} ${userargs[@]} $(cygpath -w $tlname) $(cygpath -w $modelname)"
  msg="Retranslating trace"
  echo "${msg}..."
  echo "${msg} ($callHUGO)..." >> ${logname}
  $callHUGO >${hugologname} 2>&1 ; statusHUGO=$? ; cat ${hugologname} >>${logname}
  grep "\[WARNING\]\|\[ERROR\]" ${hugologname}
  if [[ ${statusHUGO} != 0 ]]; then
    echo "Error while retranslating trace for \`$modelname', see transcript file"
    exit -1
  else
    echo "Wrote UML trail to $utlname" | tee -a ${logname}
  fi
}

function check1Uppaal {
  prepare4Uppaal
  translate2TA
  executeUppaal
  
  if tail -3 $logname | grep "Formula" | grep "NOT" >/dev/null; then
    echo "Property is NOT satisfied";
  elif tail -3 $logname | grep "Formula" | grep "MAYBE" >/dev/null; then 
    echo "Property is MAYBE satisfied";
  elif tail -3 $logname | grep "Formula is satisfied" >/dev/null; then 
    echo "Property is satisfied"
  fi
  if tail -3 $logname | grep "Showing" >/dev/null; then
    retranslate0Uppaal
  fi
}

function colour1Spin {
  collaborationname=${fulltestname%.*} # strip off trailing interaction name after .
  if [[ ${collaborationname} != ${fulltestname} ]]; then
    additionalargs[0]="--collaboration=${collaborationname}"
  else
    additionalargs[0]="--collaboration"
  fi
  testname=${fulltestname#*.} # strip off preceding collaboration name before .
  additionalargs[1]="--test=${testname}"

  prepare4Spin

  translate2Promela

  callSPIN="$SPIN -a $(cygpath -w $pmlname)"
  callGCC="$GCC -O2 -DMEMLIM=4000 -DVECTORSZ=32768 -DXUSAFE -DNOCLAIM -DCOLLAPSE -w -o panAcceptance pan.c"
  callPAN="./panAcceptance -E -A -a -n -m$MAXSEARCHDEPTH"
  msg="First colouring phase"

  executeSpin

  if grep "pan:1: acceptance cycle" $logname >/dev/null; then
    callSPIN="$SPIN -a $(cygpath -w $pmlname)"
    callGCC="$GCC -O2 -DMEMLIM=4000 -DVECTORSZ=32768 -DXUSAFE -DNP -DNOCLAIM -DCOLLAPSE -w -o panProgress pan.c"
    callPAN="./panProgress -E -l -n -m$MAXSEARCHDEPTH"
    msg="Second colouring phase"
 
    executeSpin

    if grep "pan:1: non-progress cycle" $logname >/dev/null ||
       grep "pan:1: assertion violated" $logname >/dev/null; then
      echo "Colour is YELLOW."
    else
      echo "Colour is GREEN."
    fi
  else
    echo "Colour is RED."
  fi
}

case $1 in
  "spin" )
    shift
    userargs=( $@ ) # make a copy of the arguments
    n=$(($#-1)) # get number of arguments
    if [[ $n -lt 0 ]]; then
      echo "Insufficient number of arguments"
      echo "Usage: ${0##*/} spin [options] <model>" # report command name without preceding path
      exit -1;
    fi

    echo "Hugo/RT-Spin wrapper, v0.2"

    modelname=${userargs[$n]} # get model name
    unset userargs[$n] # remove last parameter (model name)

    check1Spin
    ;;

  "uppaal" )
    shift
    userargs=( $@ ) # make a copy of the parameters
    n=$(($#-1)) # get number of parameters
    if [[ $n -lt 0 ]]; then
      echo "Insufficient number of arguments"
      echo "Usage: ${0##*/} uppaal [options] <model>" # report command name without preceding path
      exit -1;
    fi

    echo "Hugo/RT-Uppaal wrapper, v0.2"

    modelname=${userargs[$n]} # get model name
    unset userargs[$n] # remove last parameter (model name)

    check1Uppaal
    ;;

  "colour" )
    shift
    fulltestname=$1
    shift
    userargs=( $@ ) # make a copy of the arguments
    n=$(($#-1)) # get number of arguments
    if [[ $n -lt 0 ]]; then
      echo "Insufficient number of arguments"
      echo "Usage: ${0##*/} colour <testname> [options] <model>" # report command name without preceding path
      exit -1;
    fi

    echo "Hugo/RT-Colouring wrapper, v0.1"

    modelname=${userargs[$n]} # get model name
    unset userargs[$n] # remove last parameter (model name)

    colour1Spin
    ;;

  * )
    $HUGORT "$@"
esac
