#! /bin/sh
# vim:sts=2 sw=2 ts=2 et ai foldmethod=marker tw=118
#   Registration script for the backup Agent on Unix

with_buagent=0
default_wccPort=8086
register_standalone=0
debug_command=0
[ `basename ${0}` = "register" ] && register_standalone=1
register=${0}
failure=''

if [ $register_standalone -eq 1 ]; then
  trap "InstallCleanup" 0 2 3 15 ## catch EXIT, sigint, sigquit, sigterm
fi

InstallCleanup() #{{{
{
    [ -n "${config_file}" -a "${debug_command:-0}" = 0 -a -f "${config_file}" ] && rm -f "${config_file}" > /dev/null 2>&1
    LogMessage "${failure}"
} #}}}

ReadUntilSet() #{{{
{
  res=
  Prompt=${1}
  Cancel=${2}
  Variable=${3}
  Default=${4}
  Secure=${5}

  # Compensate for no default value
  if [ "${Default}" = "-secure" ]; then #{{{
    Secure=${Default}
    Default=""
  fi #}}}

  if [ "${Secure}" = "-secure" ]; then #{{{
    i=`tput setab 0` || i=
    if [ ! -z "${i}" ]; then #{{{
      i="${i}`tput setaf 0`" || i=
    fi #}}}
    n=`tput sgr0` || n=
  else
    i=
    n=
  fi #}}}

  while [ "${res}" = "" ]; do #{{{
    if [ "${Default}" != "" ]; then #{{{
      printf "${n}${Prompt}[${Default}] (\"${Cancel}\" to cancel) ${i}"
    else            
      printf "${n}${Prompt} (\"${Cancel}\" to cancel) ${i}"
    fi #}}}

    read res

    if [ "${res}" = "${Cancel}" ]; then #{{{
      return 255
    fi #}}}

    if [ "${Default}" != "" ]; then #{{{
      if [ "${res}" = "" ]; then #{{{
        res="${Default}"
      fi #}}}
    fi #}}}

    if [ "${res}" = "" ]; then #{{{
      printf "${n}Must provide a value.\n"
    fi #}}}
  done #}}}

  printf "${n}"

  eval "${Variable}=\"${res}\""
  export ${Variable}
  return 0
} #}}}

ReadPassword() #{{{
{
  unset PASSWORD
  Prompt=${1}
  Cancel=${2}

  while [ "${PASSWORD}" = "" ]; do #{{{
    printf "${Prompt} (\"${Cancel}\" to cancel) "
    # AIX doesn't have the "read -s" support, so here goes a long way to disable local echo,
    # then enable it after read
    stty_orig=`stty -g`
    stty -echo
    read PASSWORD
    stty $stty_orig
    echo

    if [ "${PASSWORD}" = "${Cancel}" ]; then #{{{
      return 255
    fi #}}}

    if [ "${PASSWORD}" = "" ]; then #{{{
      echo "Password cannot be empty. If you don't have the password, use '-' to cancel the registration."
    fi #}}}
  done #}}}

  wccPassword="${PASSWORD}"
  export wccPassword
  return 0
} #}}}

AddConsole() #{{{
{
  cmd="'${reg_dir}/buagent' --console-add ${@}"
  ${reg_dir}/buagent --console-list | grep ${1} >/dev/null || sh -c "$cmd" || failure="${failure}
    Could not register port ${1}"
} #}}}

DeleteConsoleByPortAndMode() #{{{
{
  cmd="'${reg_dir}/buagent' --console-delete-by-port-and-mode ${@}"
  ${reg_dir}/buagent --console-list | grep ${1} >/dev/null
  if [ $? -ne 0 ]
  then
      # output is empty - nothing to delete
      break
  else
      # output is non-empty - continue:
      LogMessage "Delete console port ${1}."
      sh -c "$cmd" || failure="${failure}
          Could not delete port ${1}"
  fi
} #}}}

ConfigureBUAgentPorts() #{{{
{
  # remove the existing port 8031 configuration and reconfigure it to be disabled
  # now the only way to enable it is to directly edit the buagent.cfg
  DeleteConsoleByPortAndMode 8031 'SSL'
  AddConsole 8031 'SSL'
  DeleteConsoleByPortAndMode 8021 'SSL_LOCAL'
} #}}}

NotRegistering() #{{{
{
  ConfigureBUAgentPorts
  LogMessage "Not registering to The Portal."
  return 0
} #}}}

RegisterBUAgent() #{{{
{
  replace=0

  if [ ! -z "${web_regfile}" -a -f "${web_regfile}" ]; then #{{{
    . ${web_regfile}
  fi #}}}

  for arg in "${@}"; do #{{{
    case ${arg} in #{{{
      -replace)     replace=1 ;;
      -force)       replace=1 ;;
      -address=*)   wccAddress="`ParamValue ${arg}`" ;;
      -port=*)      wccPort="`ParamValue ${arg}`" ;;
      -login=*)     wccLogin="`ParamValue ${arg}`" ;;
      -password=*)  wccPassword="`ParamValue ${arg}`" ;;
      -debug)       debug_command=1;;
    esac #}}}
  done #}}}

  if [ -z "${reg_dir}" ]; then #{{{
    source_dir="$( cd $( dirname ${0} ) >/dev/null 2>&1 && pwd )"
    [ -z "${install_dir}" ] && reg_dir="${source_dir}" || reg_dir="${install_dir}"
  fi #}}}

  if [ `uname -s` = "AIX" ]; then #{{{
      LD_LIBRARY_PATH="${reg_dir}:${LD_LIBRARY_PATH}"
      export LD_LIBRARY_PATH
  fi #}}}

  [ ${web_registration} -gt 1 ] && replace=1
  [ ${register_standalone} -eq 1 -a ! -f "${reg_dir}/buagent.cfg" ] && replace=1
  [ ! -z "${wccAddress}" -a -z "${wccPort}" ] && wccPort="${default_wccPort}"

  if [ ! -x "${reg_dir}/buagent" ]; then #{{{
    LogMessage "Cannot find ${reg_dir}/buagent. Unable to register Agent."
    return 1
  fi #}}}

  if [ -f "${reg_dir}/buagent.cfg" ]; then #{{{
    if [ ${replace} -eq 0 ]; then #{{{
      LogMessage "Already registered to the Portal."
      printf "Do you wish to register as a new computer?\n"
      printf "This will invalidate your previous registration. (y/[N]) "
      read res

      case ${res} in #{{{
        y|Y)  : ;;
        *)    LogMessage "Keeping existing Portal registration."
              ConfigureBUAgentPorts
              return
              ;;
      esac #}}}
    fi #}}}
    'cp' -f "${reg_dir}/buagent.cfg" "${reg_dir}/buagent.cfg.old"
  else
    if [ ${replace} -eq 0 ]; then #{{{
      printf "Do you wish to register to the Portal? ([Y]/n) "
      read res

      case ${res} in #{{{
        y|Y)  : ;;
        *)    [ ! -z "${res}" ] && NotRegistering && return
      esac #}}}
    fi #}}}
  fi #}}}

  if [ -z "${wccAddress}" ]; then #{{{
    ReadUntilSet "What is the Portal address? " "-" wccAddress
    if [ ${?} -ne 0 ]; then #{{{
      NotRegistering && return
    fi #}}}
  else
    LogMessage "The Portal address: ${wccAddress}"
  fi #}}}

  if [ -z "${wccPort}" ]; then #{{{
    wccPort="${default_wccPort}"
    ReadUntilSet "What is the Portal connection port? " "-" wccPort ${wccPort}
    if [ ${?} -ne 0 ]; then #{{{
      NotRegistering && return
    fi #}}}
  else
    LogMessage "The Portal port: ${wccPort}"
  fi #}}}

  if [ -z "${wccLogin}" ]; then #{{{
    ReadUntilSet "What is your Portal username? " "-" wccLogin
    if [ ${?} -ne 0 ]; then #{{{
      NotRegistering && return
    fi #}}}
  else
    LogMessage "The Portal username: ${wccLogin}"
  fi #}}}

  if [ -z "${wccPassword}" ]; then #{{{
    ReadPassword "What is your Portal password? " "-"
    if [ ${?} -ne 0 ]; then #{{{
      NotRegistering && return
    fi #}}}
  fi #}}}

  reglog="${reg_dir}/register.xlog"

  LogMessage "Registering with ${wccAddress}:${wccPort} using login of ${wccLogin}"
  oldDir=`pwd`
  cd "${reg_dir}"

  config_file="/tmp/`basename "${register}"`.$$"
  touch "${config_file}"
  chmod 600 "${config_file}"
  cat >> "${config_file}" <<EOS
ampregister=1
amplogin=${wccLogin}
amppassword=${wccPassword}
ampserver=${wccAddress}
ampport=${wccPort}
logfilename=${reglog}
EOS

  command="\"${reg_dir}/buagent\" -cmdline --config_file "${config_file}" 2>&1"

  [ ${debug_command} -eq 1 ] && echo "[${command}]"

  sh -c "${command}"

  err=${?}
  cd "${oldDir}"

  if [ ${err} -ne 0 ]; then #{{{
    LogMessage "Registration to The Portal failed."
    failure="${failure}
    Registration to The Portal failed."

    if [ -f "${reg_dir}/buagent.cfg.old" ]; then #{{{
      LogMessage "Old registration data restored."
      LogMessage "Please run ${reg_dir}/register to register the Agent with the"
      LogMessage "Portal with different credentials."

      mv "${reg_dir}/buagent.cfg.old" "${reg_dir}/buagent.cfg"
    else
      LogMessage "Please run ${reg_dir}/register to register the Agent with the Web-based"
      LogMessage "Agent Console."
    fi #}}}
  else
    LogMessage "Registered to The Portal."
    [ ${web_registration} -eq 0 ] && LogMessage "Please restart the Agent to activate the Portal connection."
  fi #}}}

  ConfigureBUAgentPorts
  [ ${debug_command} -eq 0 ] && rm -f "${config_file}"
} #}}}

if [ ${register_standalone} -eq 1 ]; then #{{{
  TestRunning() #{{{
  {
    case ${1} in #{{{
      VVAgent)  ${agentDir}/VVAgent -S > /dev/null 2>&1 
                RC=${?}
                ;;
      buagent)  ${agentDir}/buagent --status > /dev/null 2>&1 
                RC=${?}
                ;;
      *)        RC=1
    esac #}}}
    echo ${RC}
    return ${RC}
  } #}}}

  LogMessage() #{{{
  {
    [ ${#} -gt 0 ] && echo "${@}" || cat -
  } #}}}

  ParamName() #{{{
  {
    echo "${1}" | cut -f1 -d=
  } #}}}

  ParamValue() #{{{
  {
    echo "${1}" | cut -f2 -d=
  } #}}}

  web_registration=1
  web_regfile=

  sh_ext=so
  [ `uname -s` = "HP-UX" ] && sh_ext=sl

  RegisterBUAgent "${@}"

  os_name=`uname -s`
  case ${os_name} in #{{{
    AIX)    init_dir=/etc/rc.d ;;
    HP-UX)  init_dir=/sbin/init.d ;;
    Linux)  if [ -f /etc/rc.d/init.d/functions ]; then #{{{ Red Hat
              init_dir=/etc/rc.d/init.d
            elif [ -f /etc/rc.status ]; then # SUSE
              init_dir=/etc/init.d
            elif [ -f /lib/lsb/init-functions ]; then # Debian/Ubuntu
              init_dir=/etc/init.d
            else # Other
              init_dir=/etc/rc.d
            fi #}}}
            ;;
    SunOS)  init_dir=/etc/init.d ;;
  esac #}}}

  start_cmd="${init_dir}/vvagent restart quiet"
  status_cmd="${init_dir}/vvagent status quiet"
  LogMessage "Restarting Agent: ${start_cmd}"

  running=0
  timeout=0

  while [ ${running} -eq 0 -a ${timeout} -le 10 ]; do #{{{
    [ ${timeout} -ge 1 ] && LogMessage "Restarting Agent (retry ${timeout})"

    timeout=`expr ${timeout} + 1`

    sh -c "${start_cmd}" > /dev/null 2>&1

    sleep 3

    sh -c "${status_cmd}" > /dev/null 2>&1

    [ ${?} -eq 0 ] && running=1
  done #}}}

  case ${running} in #{{{
    0)  LogMessage <<EOS

Registration complete, but the Agent failed to restart. Check the log
files for more details. See the Agent release notes for possible
solutions.

EOS
        ;;
    *)  LogMessage <<EOS

Registration complete. Agent restarted successfully.

EOS
        ;;
  esac #}}}
else
  with_buagent=1

  InstallBUAgent() #{{{
  {
    InstallFile "${source_dir}/${distro}/${progbuagent}"
    InstallFile "${source_dir}/register"
    InstallFile "${source_dir}/bmrregister"
    InstallFile "${source_dir}/accesscontrol"

    if [ ${use_defaults} -ne 0 -a ${web_registration} -ne 2 ] ; then
      if [ ${web_registration} -eq 1 ] ; then
              LogMessage <<EOS
Cannot register to web-based Agent Console in default install mode without a
registration file. Use -web-registration=FILE to force registration during
installation or please run ${install_dir}/register to register
the Agent with the Portal.
EOS
      fi
      reg_dir="${install_dir}"
      NotRegistering
      return

    fi

    RegisterBUAgent
  } #}}}
fi #}}}
