#!/bin/bash
###############################################################################
# Copyright 2017 IBM Corp.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
#
###############################################################################
# COMPONENT: linkdiskandbringonline                                           #
#                                                                             #
# Links a userid disk and brings it online. Returns the address and disk info #
#                                                                             #
# Uses routines in zthinshellutils                                             #
###############################################################################


source /opt/zthin/lib/zthinshellutils
version="1.0"

###############################################################################
### FUNCTIONS #################################################################
###############################################################################

function printCMDUsage {
  : SOURCE: ${BASH_SOURCE}
  : STACK:  ${FUNCNAME[@]}
  # @Description:
  #   Prints usage help text using a list generated by previous requests made
  #   to parse the command-line argument list.
  # @Override in zthinshellutils
  # @Code:
  printf "USAGE: $CMDNAME [OPTIONS] USER_ID USERID_VDEV_TO_LINK [LINK_MODE] (default RR)\n"

  printf "${optionHelp}\n"

} #printCMDUsage{}

###############################################################################

function printCMDDescription {
  : SOURCE: ${BASH_SOURCE}
  : STACK:  ${FUNCNAME[@]}
  # @Description:
  #   Prints a short description of this command.
  # @Overrides:
  #   printCMDDescription{} in "xcatshellutils".
  # @Code:
  printf "Links a disk from a userid, onlines the disk and "
  printf "returns the linked vdev and linux device name\n"
} #printCMDDescription{}

###############################################################################

function parseArgs {
  : SOURCE: ${BASH_SOURCE}
  : STACK:  ${FUNCNAME[@]}
  # @Description:
  #   Parses and checks command-line arguments.
  # @Code:
  # Apply any defaults before handling operands


  # Non-local variables in this function are intentionally non-local.
  isOption -h --help '     Print this help message.'   && printHelp='true'
  isOption -V --version '  Print the version number of this script.'   && printVersion='true'

  # Handle options that provide info but don't deal with locks or disks
  if [[ $printVersion ]]; then
    printf "Version: $version\n\n"
  fi

  if [[ $printHelp ]]; then
    printHelp
  fi

  if [[ $printHelp || $printVersion  ]]; then
    exit 0
  fi

  # Get input parms we need
  getPositionalArg 1 userID
  getPositionalArg 2 vdev
  getPositionalArg 3 mode

  if [[ -z "$userID" ]]; then
      printf 'ERROR: Missing userid parameter.'
      printCMDUsage
      exit 1
  fi

  if [[ -z "$vdev" ]]; then
      printf 'ERROR: Missing virtual device address parameter.'
      printCMDUsage
      exit 1
  fi

  # If no link mode, default it to RR
  if [[ -z "$mode" ]]; then
      mode='RR'
  fi


  local badOptions=$(getBadOptions)
  if [[ $badOptions ]]; then
    printf "ERROR: ${badOptions}"
    printCMDUsage
    exit 1
  fi

} #parseArgs{}


###############################################################################

function linkDisk {
  : SOURCE: ${BASH_SOURCE}
  : STACK:  ${FUNCNAME[@]}
  # @Description:
  #   Calls zthinshellutils to link disk, then returns disk address and device name
  #
  # @Returns:
  #   0 if the link and online was successful. Standard out displays the linked
  #     address and the Linux device name. Linked=vdev Device='dasd... '
  #   1..5 if there was an error with connectDisk.
  #   404 If unable to find the linked vdev in table
  #   500 Failed to find a device name
  #
  # @Parameters:
  #   set by parseArgs: userID, vdev, mode=
  #
  # @Code:
  #

  local rc
  local output
  local linkedAsVdev
  local deviceName

  output=$(connectDisk $userID $vdev $mode 0)
  rc=$?

  if [[ $rc -gt 0 ]]; then
      printError "Failed to connect disk: ${userID}:${vdev} rc: ${rc}"
      printf "${output}\n"
      exit $rc
  fi

  linkedAsVdev=$(getDiskAlias $userID $vdev)
  if [ ${#linkedAsVdev} -lt 1 ]; then
      printError "Failed to find a linked vdev for: ${userID}:${vdev}"
      exit 404
  fi

  # Get the device name
  output=`cat /proc/dasd/devices | grep -a 0.0.$linkedAsVdev`
  if [ ${#output} -lt 1 ]; then
      printError "Failed to find a device name for vdev: ${vdev}"
      exit 500
  fi

  # sample output"
  # 0.0.ad35(ECKD) at ( 94:    28) is dasdh       : active at blocksize: 4096, 90000 blocks, 351 MB
  # 0.0.0444(FBA ) at ( 94:    44) is dasdl       : active at blocksize: 512, 10 blocks, 0 MB

  set -- $output

  deviceName=$7
  if [[ ".$7" == ".is" ]]; then
    # Device name is in word 8 for FBA
    deviceName=$8
  fi

  printf "Success: Userid ${userID} vdev ${vdev} linked at ${linkedAsVdev} device name ${deviceName}\n"

} #linkDisk{}

###############################################################################
### START EXECUTION ###########################################################
###############################################################################
timestamp=$(date -u --rfc-3339=ns | sed 's/ /-/;s/\.\(...\).*/.\1/')
inform "linkdiskandbringonline ${args} start time: ${timestamp}"

parseArgs
linkDisk

which udevadm &> /dev/null && udevadm settle || udevsettle

timestamp=$(date -u --rfc-3339=ns | sed 's/ /-/;s/\.\(...\).*/.\1/')
inform "linkdiskandbringonline exit time: ${timestamp}"
exit 0

###############################################################################
### END OF SCRIPT #############################################################
###############################################################################
