#!/bin/bash
# Created by Roel Van de Paar, Percona LLC

TRIAL=$(echo "$1" | sed 's|_val||' | sed 's|[ \t]*||g')  # _val: for Valgrind bugs (reducer_val{trial}.sh generated by pquery-prep-red.sh)

# Check if this is a pxc run
PXC=0
if [ "$(grep 'PXC Mode:' ./pquery-run.log 2> /dev/null | sed 's|^.*PXC Mode[: \t]*||' )" == "TRUE" ]; then
  PXC=1
fi

if [[ $PXC -eq 1 ]];then
  TRIAL_DIR=$(echo $TRIAL | sed 's/-/\/node/g')
  PXC_NODE=$(echo $TRIAL | cut -d'-' -f2)
  TRIAL=$(echo $TRIAL | cut -d'-' -f1)
fi

if [ "${TRIAL}" == "" ]; then
  echo "This script deletes a given pquery trial completely. Execute this script from within the pquery workdir"
  echo "Example: to delete trial 10 (./10), execute as: ./delete_single_trial.sh 10"
  exit 1
elif [ "`echo ${TRIAL} | sed 's|[0-9]*||'`" != "" ]; then
  echo "Trial number should be a numeric value and isn't (value passed to this script which is not considered numeric: '${TRIAL}')"
  exit 1
elif [ -d ./${TRIAL} ]; then
  # Delete trial directory
  if [[ $PXC -eq 1 ]];then
    rm -Rf ./${TRIAL_DIR} > /dev/null 2>&1
  else
    rm -Rf ./${TRIAL} > /dev/null 2>&1
  fi
else
  echo "This script deletes a given pquery trial completely. Execute this script from within the pquery workdir"
  echo "Error: trial number '${TRIAL}' was passed as an option to this script. However, no trial ${TRIAL} directory (./${TRIAL}) exists!"
  echo "Will still attempt to delete all related remaining files, if any"
fi

# Delete other files
if [[ $PXC -eq 1 ]];then
  rm -f  ./reducer${TRIAL}-${PXC_NODE}.sh > /dev/null 2>&1
  echo "- pquery trial #${TRIAL_DIR} and all related files wiped"
else
  rm -f  ./reducer${TRIAL}.sh > /dev/null 2>&1
  rm -f  ./reducer_val${TRIAL}.sh > /dev/null 2>&1
  rm -f  ./reducer${TRIAL}-*.sh > /dev/null 2>&1
  rm -f  ./${TRIAL}_bundle > /dev/null 2>&1
  rm -f  ./${TRIAL}_bundle.tar.gz > /dev/null 2>&1
  echo "- pquery trial #${TRIAL} and all related files wiped"
fi
