#!/bin/bash

set -e

START_DIR_DONT_CHANGE=`pwd`
SELF=$(basename "$0")
GEN_DATA_DIR=releng_generated_data/${SELF}
KEEP=0
SAMPLE_CODE_DIR=codesamples
CC=g++

#####################################################################
print_help() {
 cat << HLP
Usage:
 $0 -help

#
 $0 -rc [-keep]

# cleanup test generated data directory and exit
 $0 -cleanup
HLP
}

#####################################################################
cleanup() {
 if [ ${KEEP} -eq 0 ]; then
   # safety net, just in case -> we want to be in the starting
   # directory before removing whatever self-generated stuff
   if [ -d "${GEN_DATA_DIR}" ]; then
       cd "${START_DIR_DONT_CHANGE}" || exit 2
       rm -rf ${GEN_DATA_DIR}
       printf "${SELF}: Removed (self-generated) %s\n" ${GEN_DATA_DIR}
   else
       printf "${SELF}: ${GEN_DATA_DIR} does not exist. Nothing to clean.\n"
   fi
 else
   printf "${SELF}: Leaving (self-generated) %s\n" ${GEN_DATA_DIR}
 fi 
}

#####################################################################
# help
if [ ! "${1}" ]; then
 print_help && exit 3
#
elif [ "${1}" == "-cleanup" ]; then
 cleanup
 exit 0
#
elif [ "${1}" == "-rc" -a "${2}" == "-keep" ]; then
 KEEP=1
elif [ "${1}" == "-rc" -a ! "${2}" ]; then
 KEEP=0
# the rest
else
 print_help && exit 4
fi


#####################################################################
# check data dir
if [ -d "${GEN_DATA_DIR}" ]; then
 printf "\n${SELF}: directory %s exists!" ${GEN_DATA_DIR}
 printf "\n${SELF}: use '${SELF} -cleanup' to remove.\n"
 exit 5
else
 mkdir "${GEN_DATA_DIR}"
fi

# check compiler
if ! which "${CC}" >/dev/null 2>&1; then
    printf "\n${SELF}: Not found: ${CC}. Install ${CC}.\n"
    cleanup
    exit 6
fi

# process sample code tests
# if test -f "${SAMPLE_CODE_DIR}"/*.cpp; then
 for SMPL in `ls "${SAMPLE_CODE_DIR}"/*.cpp`; do
   CMD_CPL="${CC} -I../ -L ../libisoburn/.libs/ -lisoburn -o ${SMPL}.obj ${SMPL}"
   printf "${SELF}: ${CMD_CPL}\n"
   set +e
   ${CMD_CPL}
   RET_CPL="$?"
   if [ ${RET_CPL} == 0 -a -f ${SMPL}.obj ]; then
      mv ${SMPL}.obj ${GEN_DATA_DIR}
   else
      printf "\n${SELF}: FAIL Compilation of ${SMPL}\n"
      cleanup
      exit 7
   fi
   BASE=$(basename ${SMPL}.obj)
   printf "${SELF}: Running ${GEN_DATA_DIR}/${BASE}"
   ${GEN_DATA_DIR}/${BASE}
   RET_SMPL="$?"
   case ${RET_SMPL} in
    0)
     printf "...ok\n"
    ;;
    *)
     printf "exit code: ${RET_SMPL}\n"
     cleanup
     exit 8
    ;;
   esac
   set -e
 done
#else
# printf "\n${SELF}: No C++ code samples found in ${SAMPLE_CODE_DIR}\n"
#fi

# clean
cleanup

exit 0