#! /bin/bash
# Copyright © 2012-14, 2018 Richard Kettlewell.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

set -e

#echo "Running hook..."
#env | grep ^RSBACKUP | sort

# Figure out which type of hook we're looking at
hookphase="${RSBACKUP_HOOK%%-*}" # e.g. pre
hooktype="${RSBACKUP_HOOK#*-}" # e.g. volume-hook

# We'll use a .stamp file to detect hooks being run multiple times etc.
stampfile="${hooktype}.stamp"

case $hookphase in
pre )
  if [ -e ${WORKSPACE}/${stampfile} ]; then
    echo >&3 "HOOK ERROR: $RSBACKUP_HOOK: ${stampfile} already exists"
    exit 1
  fi
  touch ${WORKSPACE}/${stampfile}
  ;;
post )
  if [ ! -e ${WORKSPACE}/${stampfile} ]; then
    echo >&3 "HOOK ERROR: $RSBACKUP_HOOK: ${stampfile} does not exist"
    exit 1
  fi
  rm -f ${WORKSPACE}/${stampfile}
  ;;
* )
  echo >&3 "HOOK ERROR: unknown hook $RSBACKUP_HOOK"
  exit 1
  ;;
esac

# We'll use .ran and .acted to communicate to the test script
# that the hook ran and whether it did anything
if [ ! -z "${RUN}" ]; then
  touch ${WORKSPACE}/${RUN}-${RSBACKUP_HOOK}.ran
  if ${RSBACKUP_ACT}; then
    touch ${WORKSPACE}/${RUN}-${RSBACKUP_HOOK}.acted
  fi
fi

# Fond the stderr and status overrides
env_name=$(echo $RSBACKUP_HOOK | sed 's/-/_/g' | tr a-z A-Z) # e.g. PRE_VOLUME_HOOK

# Override stderr
stderr=$(eval echo \$${env_name}_STDERR)
case "$stderr" in
    *? )
        echo "$stderr" >&2
        ;;
esac

# Override status
status=$(eval echo \$${env_name}_STATUS)
case "$status" in
    75 )
        rm -f ${WORKSPACE}/${stampfile}
        exit "$status"
    ;;
    0 | "" )
        exit 0
    ;;
    * )
        exit "$status"
    ;;
esac
