
configVariableNameList="config_commandFile config_configFile config_FBSIPAddr config_FBSUserName config_FBSUserNamePasswd config_outputFile config_FBSWindowsUser config_FBSDomain config_FBSDirectory config_shareRepository config_FBSCmd config_FBSSnapshotTarget config_FBSSnapshotPolicy config_FBSSnapshotDate config_FBSSnapshotVolume config_FBSSnapshotServer config_FBSSnapshotRepos config_FBSISCSITarget config_MyInitiator config_ISCSITargetName config_mountPoint config_OSPlatform config_OSRedHat config_OSSuSe10 config_OSSuSe11 config_unMount config_partitionInfo"
flagVariablenameList="flag_debug flag_verbose "

for i in `echo ${configVariableNameList}`
do
  export $i
done

function verbose_print
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  if [[ -n ${flag_verbose} ]]
  then
    echo " + ${1}" | sed 's/ -p [a-z0-9A-Z]* / -p ******** /' | sed 's/ -pass [a-z0-9A-Z]* / -pass ******** /' >&2
#  else
#    echo -n "."
  fi
}

function exit_print
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  # Only print error message if verbose mode is set
  if [[ -n ${flag_verbose} ]]
  then
    echo -e " ERROR-$2- $1" | sed 's/ -p [a-z0-9A-Z]* / -p ******** /' | sed 's/ -pass [a-z0-9A-Z]* / -pass ******** /' >&2 
  fi
  exit $2
}

function exit_print_wFile
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  # Only print error message if verbose mode is set
  if [[ -n ${flag_verbose} ]]
  then
    echo -e " ERROR-$2- $1" | sed 's/ -p [a-z0-9A-Z]* / -p ******** /' | sed 's/ -pass [a-z0-9A-Z]* / -pass ******** /' >&2
  fi

  if [[ -n ${config_outputFile} ]]
  then
    echo "${2} ${1}" | sed 's/ -p [a-z0-9A-Z]* / -p ******** /' | sed 's/ -pass [a-z0-9A-Z]* / -pass ******** /' > ${config_outputFile}_rc
  fi

  exit $2
}

function warn_print
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  echo -e " WARNING: $1" >&2 | sed 's/ -p [a-z0-9A-Z]* / -p ******** /' | sed 's/ -pass [a-z0-9A-Z]* / -pass ******** /'
  verbose_print "$1"
  if [[ -n ${config_outputFile} ]]
  then
    echo -e " WARNING: $1" | sed 's/ -p [a-z0-9A-Z]* / -p ******** /' | sed 's/ -pass [a-z0-9A-Z]* / -pass ******** /' >> ${config_outputFile}
  fi 
}

function executeRemoteCommand
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  if [[ -z ${config_FBSIPAddr} ]]
  then
    exit_print_wFile " Function executeRemoteCommand requires config_FBSIPAddr is set " 1
  fi

  if [[ -z ${config_FBSWindowsUser} ]]
  then
    exit_print_wFile " Function executeRemoteCommand requires config_FBSWindowsUser is set " 1
  fi

  verbose_print "FastBack Windows Server: ${config_FBSIPAddr} User: ${config_FBSWindowsUser} Echo Output: $2"
  verbose_print "Remote Command: \"${1}\""
 
  # First lets just make sure we can connect to the Windows server and we are not
  # being prompted for a password
  verbose_print "Verify SSH Connection TimeOut Condition"
  {
     ssh -l ${config_FBSWindowsUser} ${config_FBSIPAddr} pwd > /dev/null 2>&1
  } &
  remoteCmdPID=$!
  # Wait upto 10 seconds for the pwd command to complete. If is not complete, then kill it.
  for i in `seq 1 10`
  do
    sleep 1
    if ! ps --pid ${remoteCmdPID} > /dev/null 2>&1
    then
      commandComplete=true
      break
    fi
  done

  if [[ -z ${commandComplete} ]]
  then
    # pwd command has not completed. Kill it and exit
    kill ${remoteCmdPID}
    exit_print_wFile " Command timeout on Fastback Windows Server. SSH Keys may not be configured for no password. " 40
  fi

  # Now tha we know the SSH command will not hang or prompt for FW
  # We check that there is a SSH Server listening
  verbose_print "Verify SSH Connection. No Server listening Condition "
  if ! ssh -l ${config_FBSWindowsUser} ${config_FBSIPAddr} pwd > /dev/null 2>&1
  then
    exit_print_wFile " Testing SSH Connection Failed. SSH Server may not be Configured. Failed Command: ssh -l ${config_FBSWindowsUser} ${config_FBSIPAddr} pwd " 57
  fi 

  verbose_print "Executing Command: ssh -l ${config_FBSWindowsUser} ${config_FBSIPAddr} \"${1}\""
  if [[ $# -le 1 ]]
  then
    ssh -l ${config_FBSWindowsUser} ${config_FBSIPAddr} "${1}"
    returnCode=$?
    echo ""
  elif [[ $2 = "false" ]]
  then
    ssh -l ${config_FBSWindowsUser} ${config_FBSIPAddr} "${1}" > /dev/null 2>&1
    returnCode=$?
  else
    ssh -l ${config_FBSWindowsUser} ${config_FBSIPAddr} "${1}"
    returnCode=$?
    echo ""
  fi

  verbose_print "Command Returned: ${returnCode}"

  return ${returnCode}

}

function verifySSH
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  # Verify SSH without challenge is setup
  # TODO: Need work here. This is basic
  if [[ -n ${flag_verifySSH} ]]
  then
    verbose_print "Verify SSH Key setup is complete."
    if [[ ! -d ~/.ssh ]]
    then
      exit_print_wFile " Directory ~/.ssh does not exist. SSH keys are not setup." 41
    fi

    verbose_print "Verify SSH Keys exist."
    if ! ls ~/.ssh/*pub > /dev/null 2>&1
    then
      exit_print_wFile " No public keys found in ~/.ssh. SSH Keys are not setup." 42
    fi

    verbose_print "Verfiy Connection to FastbackShell Server"
    if ! executeRemoteCommand "pwd" false
    then
      exit_print_wFile " Connection to FastbackShell Server Failed" 43
    fi
  fi
}

# FUNCTION: READ NULL LINES
# Reads from STDIN until a non NULL line is encountered
#
# Post Conditions
#       Variable ${REPLY} has the next non-null line encountered
function read_null_lines
{
        while true
        do
                # If the read fails, must be end of file
                if ! read
                then
                        #printf "\n"
                        return 1
                fi
                if [[ -n ${REPLY} ]]
                then
                        return 0
                fi
        done
}

function convertDate_one
{
  # Converts date like "2009-Sep-03 15:00:01" to "2009-09-03 15:00:01"

  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  dateToConvert=$1

  typeset -u monthToConvert
  monthToConvert=`echo ${dateToConvert} | awk -F '-' '{print $2}'`

  case ${monthToConvert} in
    "JAN") convertedMonth=1;;
    "FEB") convertedMonth=2;;
    "MAR") convertedMonth=3;;
    "APR") convertedMonth=4;;
    "MAY") convertedMonth=5;;
    "JUN") convertedMonth=6;;
    "JUL") convertedMonth=7;;
    "AUG") convertedMonth=8;;
    "SEP") convertedMonth=9;;
    "OCT") convertedMonth=10;;
    "NOV") convertedMonth=11;;
    "DEC") convertedMonth=12;;
    *) exit_print_wFile "Invalid date. Month: ${monthToConvert}" 1;; 
  esac

  echo ${dateToConvert} | awk -F '-' '{print $1"-"'${convertedMonth}'"-"$3}'
}

function loadConfigFile 
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  verbose_print "Command Filename is ${config_commandFile}"
  verbose_print "Config Filename is ${config_configFile}"

  verbose_print "Verify Config Filename exists and is not empty."
  if [[ ! -s ${config_configFile} ]]
  then
    exit_print " Config Filename does not exist or is zero length \n  Filename: ${config_configFile}" 44
  fi

  verbose_print "Verify Config Filename is not a directory."
  if [[ -d ${config_configFile} ]]
  then
    exit_print " Config Filename cannot be a directory \n  Filename: ${config_configFile}" 45
  fi

  # Bring in the config file
  # TODO:
  #. ${config_configFile}
}

function getOSPlatform
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  if [[ -a /etc/redhat-release ]]
  then
    verbose_print "Found file /etc/redhat-release: `cat /etc/redhat-release | head -n 1`"
    cat /etc/redhat-release | head -n 1
    return 10
  elif [[ -a /etc/SuSE-release ]]
  then
    verbose_print "Found file /etc/SuSE-release: `cat /etc/SuSE-release | head -n 1`"
    if cat /etc/SuSE-release | grep "VERSION = 10" > /dev/null 2>&1
    then
      verbose_print "Found SLES 10 Platform"
      return 11
    elif cat /etc/SuSE-release | grep "VERSION = 11" > /dev/null 2>&1
    then
      verbose_print "Found SLES 11 Platform"
      return 12
    else
      verbose_print "Unknown SLES Version. Unknown OS platform"
      echo "Unknown"
    fi
  else 
    verbose_print "Did not find /etc/redhat-release or /etc/SuSE-release. Unknown OS platform"
    echo "Unknown"
    return 1
  fi 
  return 1
}

function checkFastBackServerDependancies
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  verbose_print "Checking FastBackServer Dependancies"

  dependanciesMet="false"

  verbose_print "Checking cygdrive-prefix is set"
  if ! executeRemoteCommand "mount" false
  then
    exit_print_wFile " \"mount\" command not sucessful on FastBack Server." 34
  fi

  executeRemoteCommand "mount -p | tail -n 1" | {
    while read_null_lines
    do
      verbose_print "Found Prefix Line: ${REPLY}"
      thisPrefix=`echo ${REPLY} | awk '{print $1}'`
      verbose_print "Found Prefix: ${thisPrefix}"
      if [[ ${thisPrefix} != "/" ]]
      then
        exit_print_wFile " The Cygwin Prefix is not set to /. Current prefix: ${thisPrefix}" 60
      fi
    done
  }

  verbose_print "Verify FastBackServer is installed"
  if ! executeRemoteCommand 'REG QUERY HKLM\\\SYSTEM\\\CurrentControlSet\\\Services\\\FastbackServer' false
  then
    verbose_print "Key not found at HKLM/SYSTEM/CurrentControlSet/Services/FastbackServer. FastBackServer not installed"
    if ! executeRemoteCommand 'REG QUERY HKLM\\\SYSTEM\\\CurrentControlSet\\\Services\\\FastbackDRHubServer' false
    then
      verbose_print "Key not found at HKLM/SYSTEM/CurrentControlSet/Services/FastbackDRHubServer. FastBackServer not installed"
    else
      verbose_print "FastBack Hub Installed"
      dependanciesMet="true"
    fi
  else
    verbose_print "FastBack Server Installed"
    dependanciesMet="true"
  fi

  if [[ ${dependanciesMet} = "true" ]]
  then
    if ! executeRemoteCommand 'REG QUERY HKLM\\\SYSTEM\\\CurrentControlSet\\\Services\\\FastbackMount' false
    then
      verbose_print "FastBackMount not installed. key not found at HKLM/SYSTEM/CurrentControlSet/Services/FastbackMount"
      dependanciesMet="false"
    else
      verbose_print "FastBack Mount Installed"
    fi
  fi
 
  if [[ ${dependanciesMet} = "false" ]]
  then  
    exit_print_wFile "FastBack Dependancies not meti. FastBackServer with FastBackMount or FastBack Hub with FastBackMount must be installed." 46
  fi
}

function checkLocalDependancies
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  verbose_print " Verify script is running as root user"
  if [[ `id -u` -ne "0" ]]
  then
    exit_print_wFile " You must run this script as root user" 47
  fi

  if [[ ${config_OSRedHat} = "true" ]]
  then
    verbose_print "RH 5.3 Platform. Checking for packages"
    if ! rpm -qa | grep iscsi-initiator-utils > /dev/null 2>&1
    then
      exit_print_wFile "iscsi-initiator-utils package not installed. Package is required." 48
    fi
    verbose_print "RH 5.3 Platform. Checking for scsi package"
    if ! rpm -qa | grep ^lsscsi- > /dev/null 2>&1
    then
      exit_print_wFile "lsscsi package not installed. Package is required." 51
    fi
    verbose_print "RH 5.3 Platform. Checking for openssh package"
    if ! rpm -qa | grep ^openssh-clients > /dev/null 2>&1
    then
      exit_print_wFile "openssh-clients package not installed. Package is required." 52
    fi
    verbose_print "RH 5.3 Platform. Checking for util-linux package"
    if ! rpm -qa | grep ^util-linux > /dev/null 2>&1
    then
      exit_print_wFile "util-linux package not installed. Package is required." 53
    fi
  elif [[ ${config_OSSuSe10} = "true" ]]
  then
    verbose_print "SLES10 Platform. Checking for open-iscsi package"
    if ! rpm -qa | grep open-iscsi > /dev/null 2>&1
    then
      exit_print_wFile "open-iscsi package not installed. Package is required." 54
    fi
    verbose_print "SLES10 Platform. Checking for scsi package"
    if ! rpm -qa | grep ^scsi- > /dev/null 2>&1
    then
      exit_print_wFile "scsi package not installed. Package is required." 55
    fi
    verbose_print "SLES10 Platform. Checking for openssh package"
    if ! rpm -qa | grep ^openssh > /dev/null 2>&1
    then
      exit_print_wFile "openssh package not installed. Package is required." 56
    fi
    verbose_print "SLES10 Platform. Checking for util-linux package"
    if ! rpm -qa | grep ^util-linux > /dev/null 2>&1
    then
      exit_print_wFile "util-linux package not installed. Package is required." 53
    fi
  elif [[ ${config_OSSuSe11} = "true" ]]
  then
    verbose_print "SLES11 Platform. Checking for open-iscsi package"
    if ! rpm -qa | grep open-iscsi > /dev/null 2>&1
    then
      exit_print_wFile "open-iscsi package not installed. Package is required." 54
    fi
    verbose_print "SLES11 Platform. Checking for lsscsi package"
    if ! rpm -qa | grep ^lsscsi- > /dev/null 2>&1
    then
      exit_print_wFile "scsi package not installed. Package is required." 55
    fi
    verbose_print "SLES11 Platform. Checking for openssh package"
    if ! rpm -qa | grep ^openssh > /dev/null 2>&1
    then
      exit_print_wFile "openssh package not installed. Package is required." 56
    fi
    verbose_print "SLES11 Platform. Checking for util-linux package"
    if ! rpm -qa | grep ^util-linux > /dev/null 2>&1
    then
      exit_print_wFile "util-linux package not installed. Package is required." 53
    fi
  else
    exit_print_wFile " Function checkDependancies requires config_OSRedHat or config_OSSuSe is set. " 1
  fi
}

function getFastBackShellDir
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  verbose_print "Query the Windows Repository for the FastBack shell Install Location."
  if ! executeRemoteCommand 'REG QUERY HKLM\\\SOFTWARE\\\IBM\\\FastBack /v InstallPath' false
  then
    verbose_print "Query the Windows Repository for the FastBack 64bit Install Location."
    if ! executeRemoteCommand 'REG QUERY HKLM\\\SOFTWARE\\\Wow6432Node\\\FastBack /v InstallPath' false
    then
      verbose_print "Unable to retreive FastBackShell locaion. No registry at HKLM\\SOFTWARE\\IBM\\FastBack /v InstallPath or HKLM\\SOFTWARE\\Wow6432Node\\FastBack /v InstallPath"
      chkShellDirForSvrSix="true"
    else
      tmpPath=`executeRemoteCommand 'REG QUERY HKLM\\\SOFTWARE\\\Wow6432Node\\\FastBack /v InstallPath' | grep InstallPath | awk '{for(i=3;i<=NF;i++) printf("%s ",$i)}' | tr -d '\r'`
    fi
  else
    tmpPath=`executeRemoteCommand 'REG QUERY HKLM\\\SOFTWARE\\\IBM\\\FastBack /v InstallPath' | grep InstallPath | awk '{for(i=3;i<=NF;i++) printf("%s ",$i)}' | tr -d '\r'`
  fi

  if [[ ! -z ${chkShellDirForSvrSix} ]]
  then
    verbose_print "Query the Windows Repository for the FastBack shell Install Location. Server Version 6"
    if ! executeRemoteCommand 'REG QUERY HKLM\\\SOFTWARE\\\Wow6432Node\\\IBM\\\FastBack /v InstallPath' false
    then
      exit_print_wFile " Unable to retreive FastBackShell locaion. No registry at HKLM\\\SOFTWARE\\\Wow6432Node\\\IBM\\\FastBack /v InstallPath" 58
    else
      tmpPath=`executeRemoteCommand 'REG QUERY HKLM\\\SOFTWARE\\\Wow6432Node\\\IBM\\\FastBack /v InstallPath' | grep InstallPath | awk '{for(i=3;i<=NF;i++) printf("%s ",$i)}' | tr -d '\r'`
    fi
  fi

  verbose_print "Windows Location of Fastback Instalation: ${tmpPath}"
  typeset -l tmpDriveLetter
  tmpDriveLetter=`echo -n ${tmpPath} | awk -F ":" '{print $1}'`

  #Convert to Cygwin path. Escaping all the backspaces and spaces thru all the shells is difficult.
  tmpPath=`echo -n ${tmpPath} | awk -F '\' '{for(i=2;i<=NF;i++) printf("/%s",$i)}' | tr -d '\r'`
  verbose_print "FastBack Install Location: /${tmpDriveLetter}${tmpPath}shell"
  echo -n "/${tmpDriveLetter}/${tmpPath}shell"
}

function hostnameToIP
{
  if [[ -n ${flag_debug} ]]
  then
    set -x
  fi

  if [[ ! $# -eq 1 ]]
  then
    exit_print_wFile " Function: hostnameToIP takes exactly 1 argument: hostname" 1
  fi

  tmpHostname=$1
  verbose_print "Checking if ${tmpHostname} is a hstname or IP"

  if echo ${tmpHostname} | grep -w '[0-9]\{1,\}.[0-9]\{1,\}.[0-9]\{1,\}.[0-9]\{1,\}' > /dev/null 2>&1
  then
    verbose_print "${tmpHostname} is a IPV4 IP"
    echo ${tmpHostname}
  elif echo ${tmpHostname} | grep ':' > /dev/null 2>&1
  then
    verbose_print "${tmpHostname} is a IPV6 IP"
    echo ${tmpHostname}
  else
    verbose_print "${tmpHostname} is a hostname"
    if ! host ${tmpHostname} > /dev/null 2>&1
    then
      exit_print_wFile " Local System Command Faled: host ${tmpHostname} " 1
    fi
    host ${tmpHostname} | awk '{print $NF}'
    verbose_print "hostname: ${tmpHostname} IP: `host ${tmpHostname} | awk '{print $NF}'`"
  fi
}

