#! /bin/sh
# vim:sts=2 sw=2 ts=2 et ai foldmethod=marker tw=118
#   Script to get ReaR tool executable path and add it to Global.vvc

if [ "$(command -v LogMessage)x" != "LogMessagex" ]; then
  LogMessage()
  {
    [ ${#} -gt 0 ] && echo "${@}" || cat -
  }
fi

if [ "$(command -v FailInstall)x" != "FailInstallx" ]; then
  INSTALL_FAILED=2
  FailInstall()
  {
    errorCode=${1}
    shift
    errorMessage="${*}"

    LogMessage <<EOS

Installation failed.
    ${errorMessage}

EOS

    exit ${errorCode}
  }
fi

if [ "$(command -v DownCase)x" != "DownCasex" ]; then
  DownCase()
  {
    echo ${1} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'
  }
fi

if [ "$(command -v ParamValue)x" != "ParamValuex" ]; then
  ParamValue()
  {
    echo "${1}" | cut -f2 -d=
  }
fi

ValidateReaRPath()
{
  if [ -n "${rear_path}" -a ! -e "${rear_path}" ]; then
    LogMessage "'${rear_path}' does not exist."
    rear_path=
  fi
  if [ -n "${rear_path}" -a ! -f "${rear_path}" ]; then
    LogMessage "'${rear_path}' is not a file."
    rear_path=
  fi
  if [ -n "${rear_path}" -a ! -x "${rear_path}" ]; then
    LogMessage "'${rear_path}' is not an executable."
    rear_path=
  fi
}

SetReaRPath()
{
  command="\"${install_dir}/buagent\" --setrearpath \"${rear_path}\" 2>&1"
  sh -c "${command}"
  err=${?}

  if [ ${err} -ne 1 ]; then
    LogMessage "Could not set the Relax-and-Recover tool path."
  else
    SetReaRRestoreVVPath
  fi
}

# create '/usr/share/rear/restore/VV' folder
SetReaRRestoreVVPath()
{
  # remove sbin/rear from rear path
  base_restore_VV_path="${rear_path%sbin/rear}"
  restore_VV_path="${base_restore_VV_path}share/rear/restore/VV"
  if [ ! -d ${restore_VV_path} ]; then
    LogMessage "Creating restore VV path '${restore_VV_path}'."
    mkdir -p ${restore_VV_path}
  fi
}

GetReaRPath()
{
  local firsttime=1
  while [ true ]; do
    if [  "`DownCase ${enable_bmr}`" = "n" ]; then
      LogMessage "BMR will not be enabled."
      rear_path=
      return
    else if [  "`DownCase ${enable_bmr}`" != "y" ]; then
      res=""
      while [ "${res}" = "" ]; do
        echo -n "Do you want to enable Bare Metal Restore (BMR) ([Y]/n)? "

        read res

        if [ "${res}" = "n" ]; then
          LogMessage "BMR will not be enabled."
          rear_path=
          return
        fi

        if [ "${res}" = "" ]; then
          res="y"
        fi

        if [ "`DownCase ${res}`" != "y" ]; then
          res=""
        fi
      done
      echo
    fi
    fi

    if [ ${firsttime} -eq 1 ]; then
      LogMessage <<EOS
The Relax-and-Recover tool is required for BMR. You can download the tool
from https://relax-and-recover.org/.

EOS
      firsttime=0
    fi

    ValidateReaRPath
    if [ -z "${rear_path}" ]; then
      echo -n "Enter the path to the Relax-and-Recover tool required for BMR (${old_rear_path}): "
      read rear_path
      if [ -z "${rear_path}" ]; then
        rear_path=${old_rear_path}
      fi
      ValidateReaRPath
    fi

    if [ -n "${rear_path}" ]; then
      LogMessage "BMR will be enabled."
      LogMessage "Setting the Relax-and-Recover tool path to ${rear_path}."
      return
    fi
  done
}

SetBMR()
{
  use_defaults=${use_defaults:-0}

  if [ -z "${install_dir}" ]; then
    if [ -f Global.vvc ]; then
      install_dir=$(pwd)
    else
      # the directory of the bmrregister script
      install_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
    fi
  fi

  enable_bmr=
  rear_path=
  old_rear_path=

  for arg in "${@}"; do
    case "${arg}" in
      -enable-bmr=*)  enable_bmr=$(ParamValue "${arg}") ;;
      -rear-path=*)   rear_path=$(ParamValue "${arg}") ;;
    esac
  done

  if [ -z "${rear_path}" ]; then
    if [ -f ${install_dir}/Global.vvc ]; then
      old_rear_path=$(grep 'ReaR_Path' ${install_dir}/Global.vvc | sed 's/[[:space:]]//g' | cut -d '=' -f 2)
    fi
  else
    old_rear_path=${rear_path}
  fi

  if [ ${use_defaults} -eq 1 ]; then
    if [ -z "${rear_path}" ]; then
      rear_path=${old_rear_path}
    fi
    if [ -z "${enable_bmr}" ]; then
      if [ -z "${rear_path}" ]; then
        enable_bmr=n
      else
        enable_bmr=y
      fi
    fi
    if [ "`DownCase ${enable_bmr}`" = "n" ]; then
      rear_path=
      SetReaRPath
      return
    fi

    ValidateReaRPath
    if [ -z "${rear_path}" ]; then
      FailInstall ${INSTALL_FAILED} "Cannot enable BMR. The Relax-and-Recover tool path is invalid or not set."
    fi
    SetReaRPath
    return
  fi

  if [ "`DownCase ${enable_bmr}`" = "n" ]; then
    rear_path=
    SetReaRPath
    return
  fi

  GetReaRPath
  SetReaRPath
  return
}

ValidateBMRAndAccessRestriction()
{
  if [ ${pluginInstall} -eq 0 ]; then
    #verify access restriction and BMR are not both enabled
    enable_bmr=
    access_setting=
    access_set=0
    for arg in "${@}"; do
      case "${arg}" in
        -enable-bmr=*)  enable_bmr=$(ParamValue "${arg}") ;;
        -setaccess=*|-ACC=*)  access_setting=$(ParamValue "${arg}")
                              access_set=1 ;;
      esac
    done
    old_access_allowed=
    old_rear_path=
    if [ -f "${install_dir}/Global.vvc" ]; then
      old_access_allowed=$(grep 'AccessAllowed' ${install_dir}/Global.vvc | sed 's/[[:space:]]//g' | cut -d '=' -f 2)
      old_rear_path=$(grep 'ReaR_Path' ${install_dir}/Global.vvc | sed 's/[[:space:]]//g' | cut -d '=' -f 2)
    fi

    if [ ${access_set} -eq 1 -a -n "${access_setting}" -a \
         "`DownCase ${enable_bmr}`" = "y" ]; then
      FailInstall ${INSTALL_FAILED} "Cannot enable both Bare Metal Restore (BMR) and folder restrictions."
    fi
    if [ "`DownCase ${enable_bmr}`" = "y" -a \
         -n "${old_access_allowed}" -a \
         \( ${access_set} -eq 0 -o -n "${access_setting}" \) ]; then
      FailInstall ${INSTALL_FAILED} "Cannot enable Bare Metal Restore (BMR) because folder restrictions are set."
    fi
    if [ ${access_set} -eq 1 -a -n "${access_setting}" -a \
         -n "${old_rear_path}" -a \
         "`DownCase ${enable_bmr}`" != "n" ]; then
      FailInstall ${INSTALL_FAILED} "Cannot set folder restrictions because Bare Metal Restore (BMR) is enabled."
    fi
  fi
}

if [ "$(basename "${0}")" = "bmrregister" ]; then
  if [ -f ${install_dir}/Global.vvc ]; then
    old_access_allowed=$(grep 'AccessAllowed' ${install_dir}/Global.vvc | sed 's/[[:space:]]//g' | cut -d '=' -f 2)
    if [ -n "${old_access_allowed}" ]; then
      LogMessage "Cannot enable BMR because folder restrictions are set."
      exit 1
    fi
  fi
  SetBMR "$@"
  /etc/init.d/vvagent restart
fi

