function echoBig {
  echo ""
  echo "*************************************"
  echo $1
  echo "*************************************"
  echo ""
}

function myExit {
  echo "Oops! Something went wrong and the program exited with code $1"
  echo "Check the logs directory: ($2) for the reason why!"
  echo "Ensure you run the command ./cleanupRDQM.sh before trying again."
}

function removeTroublesomeVG {
  VG=$1
  dd if=/dev/zero of=/tmp/tmp.raw bs=1M count=100
  device=$(losetup -f)
  losetup $device /tmp/tmp.raw
  vgextend $VG $device
  vgremove $VG --force
  pvremove $device
}

function initRDQMSetup {
  unset IFS
  user=mqm
  node1=${basehostname}1.fyre.ibm.com
  node2=${basehostname}2.fyre.ibm.com
  node3=${basehostname}3.fyre.ibm.com
  sshCommand="ssh -o StrictHostKeyChecking=no"
  logsDir=/tmp/rdqm-logs/$(date +%d%m%y%H%M%S)
  echoBig "see $logsDir for logs of the run!"
  mkdir -p $logsDir
  chmod 777 $logsDir
  $sshCommand root@$node2 "mkdir -p $logsDir; chmod 777 $logsDir"
  $sshCommand root@$node3 "mkdir -p $logsDir; chmod 777 $logsDir"
}


function createVGdrbdpoolOld {
  node=$1
  sshNode="$sshCommand root@$node"
  rc=$($sshNode "vgs | grep drbdpool >$logsDir/findDrbdpool; echo \$?")
  if [ $rc == 0 ]
  then
    echoBig "drbdpool volume group already exists on $node"
  else

    echoBig "Creating MQ drbdpool VG on $node"

    i=1
    while [ $($sshNode "ls ~/disk$i.img") ]
    do
      echo "~/disk$i.img already exists"
      i=$[$i+1]
    done

    rc=$($sshNode "truncate -s 10G ~/disk$i.img >$logsDir/truncate 2>&1; echo \$?")

    if [ $rc != 0 ]
    then
      echo "Failed to create a 10GB file called ~/disk$i on $node"
      myExit $rc $logsDir/truncate
      return 1
    fi

    rc=$($sshNode "echo -e \"0,\\n;\\n;\" | sfdisk ~/disk$i.img >$logsDir/sfdisk 2>&1; echo \$?")

    if [ $rc != 0 ]
    then
      echo "Failed to run sfdisk on ~/disk$i on $node"
      myExit $rc $logsDir/sfdisk
      return 1
    fi

    rc=$($sshNode "sudo losetup -P $(losetup -f) ~/disk$i.img >$logsDir/losetup-P 2>&1; echo \$?")

    if [ $rc != 0 ]
    then
      echo "Failed to run losetup -P on ~/disk$i on $node"
      myExit $rc $logsDir/losetup-P
      return 1
    fi

    loopdevices=$($sshNode "sudo losetup -a | grep disk$i.img | cut -f1 -d: | sed -e 's/\/.*\///'");

    if [ $($sshNode "echo $loopdevices | wc -w") != 1 ] || [ $($sshNode echo $loopdevices | wc -l) != 1 ]
    then
      echo "More than one or no loopdevices attached to ~/disk$i on $node. Cannot continue"
      myExit $rc $logsDir/losetup-P
      return 1
    fi

    device=/dev/$($sshNode "cat /proc/partitions | grep \"${loopdevices}p\" | awk -F\  '{print \$NF}'")

    if [ $device = "/dev/" ]
    then
      echo "Failed to find a usable device for drbdpool VG on $node. Cannot continue!"
      myExit $rc $logsDir
      return 1
    fi

    rc=$($sshNode "sudo pvcreate $device >$logsDir/pvcreate 2>&1; echo \$?")
    if [ $rc != 0 ]
    then
      echo "Failed to run pvcreate for $device on $node. Cannot continue!"
      myExit $rc $logsDir/pvcreate
      return 1
    fi

    rc=$($sshNode "sudo vgcreate drbdpool $device >$logsDir/vgcreate  2>&1; echo \$?")
    if [ $rc != 0 ]
    then
      echo "Failed to run vgcreate for $device on $node. Cannot continue!"
      myExit $rc $logsDir/vgcreate
      return 1
    fi

    echoBig "Successfully created 'drbdpool' Volume Group on $node under ~/disk$i.img and pv $device"

  fi
}

function createVGdrbdpool {
  node=$1
  sshNode="$sshCommand root@$node"

  rc=$($sshNode "vgs | grep drbdpool >$logsDir/findDrbdpool; echo \$?")

  if [ $rc == 0 ]
  then
    echoBig "drbdpool volume group already exists on $node"
  else

    echoBig "Creating MQ drbdpool VG on $node"

    i=1
    while [ $($sshNode "ls ~/disk$i.img") ]
    do
      echo "~/disk$i.img already exists"
      i=$[$i+1]
    done

    rc=$($sshNode "truncate -s 10G ~/disk$i.img >$logsDir/truncate 2>&1; echo \$?")

    if [ $rc != 0 ]
    then
      echo "Failed to create a 10GB file called ~/disk$i on $node"
      myExit $rc $logsDir/truncate
      return 1
    fi

    DEVICE=$($sshNode "losetup --show -f ~/disk$i.img")

    rc=$($sshNode "mkfs.ext4 -F $DEVICE >$logsDir/mkfs 2>&1; echo \$?")

    if [ $rc != 0 ]
    then
      echo "Failed to create a 10GB file called ~/disk$i on $node"
      myExit $rc $logsDir/truncate
      return 1
    fi

    rc=$($sshNode "vgcreate --force drbdpool $DEVICE >$logsDir/vgcreate 2>&1; echo \$?")

    if [ $rc != 0 ]
    then
      echo "Failed to create a volume group called drbdpool from device: $DEVICE on $node"
      myExit $rc $logsDir/vgcreate
      return 1
    fi

    rc=$($sshNode "echo losetup -f ~/disk$i.img >> /etc/rc.local; echo \$?")

    if [ $rc != 0 ]
    then
      echo "Failed to write \"losetup -f ~/disk$i.img\" to /etc/rc.local on $node"
      myExit $rc $logsDir/rc.local
      return 1
    fi

    echoBig "Successfully created 'drbdpool' Volume Group on $node under ~/disk$i.img and pv $DEVICE"

  fi
}

############################
# Remove drbdpool VG       #
############################
function removeVGdrbdpool {
  node=$1
  sshNode="$sshCommand root@$node"
  rc=$($sshNode "vgs | grep drbdpool >$logsDir/findDrbdpool; echo \$?")
  if [ $rc != 0 ]
  then
    echoBig "drbdpool volume group doesn't exist on $node"
  else
    physical_volumes=$($sshNode "pvdisplay -S vg_name=drbdpool -C 2>/dev/null | grep /dev | cut -f3 -d' '")

    rc=$($sshNode "vgremove drbdpool >$logsDir/vgremove 2>&1; echo \$?")
    if [ $? == 0 ]
    then
      echo "drbdpool VG successfully removed on $node"
    else
      echo "drbdpool VG could not be removed on $node (rc = $?)"
      myExit $rc $logsDir/vgremove
      return 1
    fi

    rc=$($sshNode "pvremove $physical_volumes >$logsDir/pvremove 2>&1; echo \$?")
    if [ $? == 0 ]
    then
      echo "PV(s) $physical_volumes successfully removed on $node"
    else
      echo "PV(s) $physical_volumes could not be removed on $node (rc = $?)"
      myExit $rc $logsDir/pvremove
      return 1
    fi

    loopDevice=$($sshNode lsblk --output PKNAME -n $physical_volumes)

    if [ -z $loopDevice ]
    then
      echo "Could not find loop device for $physical_volumes on $node"
      return 1
    fi

    rc=$($sshNode "losetup -D $physical_volumes >$logsDir/losetup-d 2>&1; echo \$?")

    if [ $? == 0 ]
    then
      echo "Loopback device(s) $loopDevice successfully removed on $node"
    else
      echo "Loopback device(s) $loopDevice could not be removed on $node (rc = $?)"
      myExit $rc $logsDir/losetup-d
      return 1
    fi

  fi
}

function addMQMToSudoers {
  node=$1
  sshNode="$sshCommand root@$node"

  sudoersCmd="$user ALL=(ALL) NOPASSWD: /opt/mqm/bin/crtmqm, /opt/mqm/bin/dltmqm, /opt/mqm/bin/rdqmadm, /opt/mqm/bin/rdqmstatus, /opt/mqm/bin/endmqm\n"
  rc=$($sshNode "echo -e \"$sudoersCmd\" >> /etc/sudoers; echo \$?")
  if [ $rc == 0 ]
  then
    echo "$sudoersCmd successfully added to /etc/sudoers on $node"
  else
    echo "$sudoersCmd could not be added to /etc/sudoers on $node (rc = $rc)"
    return 1
  fi
}

function addPasswordlessSSH {
  from_node=$1
  to_node=$2

  rc=$($sshCommand root@$from_node "scp -o StrictHostKeyChecking=no /home/$user/.ssh/id_rsa.pub root@$to_node:/home/$user/.ssh/id_rsa_$from_node.pub >$logsDir/copyPublicKey_${from_node}_${to_node} 2>&1; echo \$?")
  if [ $rc != 0 ]
  then
    echo "Could not copy id_rsa.pub on $from_node to id_rsa_$from_node.pub on $to_node (rc = $rc)"
    myExit $rc $logsDir/copyPublicKey_${from_node}_${to_node}
    return 1
  fi

  rc=$($sshCommand root@$to_node "cat /home/$user/.ssh/id_rsa_$from_node.pub  >> /home/$user/.ssh/authorized_keys; chmod 644 /home/$user/.ssh/authorized_keys >$logsDir/addAuthorizedKey_${from_node}_${to_node} 2>&1; echo \$?")
  if [ $rc != 0 ]
  then
    echo "Could not add id_rsa_$from_node.pub to authorized_keys on $to_node (rc = $rc)"
    myExit $rc $logsDir/addAuthorizedKey_${from_node}_${to_node}
    return 1
  fi
}

function generateSSHKey {
  node=$1
  rc=$($sshCommand root@$node "echo y | ssh-keygen -t rsa -f /home/$user/.ssh/id_rsa -N '' >$logsDir/generateSSHKey 2>&1; echo \$?")
  if [ $rc != 0 ]
  then
    echo "Could not Generated SSHKey on $node (rc = $rc)"
    myExit $rc $logsDir/generateSSHKey
    return 1
  else
    echo "Generated SSHKey on $node successfully"
    rc=$($sshCommand root@$node "chown $user:$user /home/$user/.ssh/id_rsa >$logsDir/chownSSHKey 2>&1; echo \$?")
    if [ $rc != 0 ]
    then
      echo "Could not chown SSHKey on $node (rc = $rc)"
      myExit $rc $logsDir/chownSSHKey
      return 1
    else
      echo "Chowned SSHKey on $node successfully"
    fi
  fi
}

function setMQInst {
  node=$1
  rc=$($sshCommand root@$node "/opt/mqm/bin/setmqinst -p /opt/mqm/ -i; >$logsDir/setmqinst 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echoBig "setmqinst run successfully on $node."
  else
    echoBig "Couldn't set MQ $mq_level as primary install on $node"
    myExit $rc $logsDir/setmqinst
    return $rc
  fi
}

function installRDQM {
  node=$1
  sshNode="$sshCommand root@$node"
  rc=$($sshNode "rpm -qa | grep MQSeries >$logsDir/checkAlreadyInstalled 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echoBig "MQ already installed on $node."
  else
    echoBig "Installing MQ $mq_level on $node"
    rc=$($sshNode "/tmp/mq/mqlicense.sh -accept >$logsDir/installRDQM 2>&1; /tmp/mq/Advanced/RDQM/installRDQMsupport >>$logsDir/installRDQM  2>&1; echo \$?")
    if [ $rc == 0 ]
    then
      echo "MQ $mq_level successfully installed on $node"
    else
      echoBig "Couldn't install MQ $mq_level on $node"
      myExit $rc $logsDir/installRDQM
      return $rc
    fi
  fi
}

function copyMQBinOrLibToNode {
  node=$1
  location=$2
  remoteUser=$3
  remotePassword=$4
  sshNode="$sshCommand root@$node"
  rsync_cmd="/usr/bin/rsync -ratlz --rsh=\"/usr/bin/sshpass -p $remotePassword $sshCommand -l $user\""

  rc=$($sshNode "ls /tmp/mq/MQSeries* >$logsDir/mkdirTmpMq 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echoBig "MQ already exists on $node so skipping copy, you might want to run cleanupRDQM.sh to remove it."
  else
    rc=$($sshNode "$rsync_cmd $remoteUser@$location /tmp/mq >$logsDir/rsync  2>&1; echo \$?")
    if [ $rc == 0 ]
    then
      echo "MQ $mq_level successfully copied to $node"
    else
      echoBig "Couldn't copy MQ $mq_level to $node"
      myExit $rc $logsDir/rsync
      return $rc
    fi
  fi
}

function chmodFileOnNode {
  node=$1
  permissions=$2
  file=$3
  sshNode="$sshCommand root@$node"

  rc=$($sshNode "chmod $permissions $file >$logsDir/mkdirTmpMq 2>&1; echo \$?")
  if [ $rc != 0 ]
  then
    echoBig "Failed chmodding $file on $node"
    return $rc
  fi

  return $rc
}

function copyFileToNode {
  node=$1
  filePathToGrab=$2
  destFilePathToGrab=$3
  remoteUser=$4
  remotePassword=$5
  sshNode="$sshCommand root@$node"
  rsync_cmd="/usr/bin/rsync -ratlz --rsh=\"/usr/bin/sshpass -p $remotePassword $sshCommand -l $user\""

  rc=$($sshNode "$rsync_cmd $remoteUser@$filePathToGrab $destFilePathToGrab >$logsDir/rsync  2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echoBig "$filePathToGrab successfully copied to $node"
  else
    if [ $rc == 23 ]
    then
      echoBig "Couldn't copy $filePathToGrab to $node (Didn't exist)!"
    else
      echoBig "Couldn't copy $filePathToGrab to $node"
    fi
    return $rc
  fi
}

function copyMQToNode {
  node=$1
  location=$2
  remoteUser=$3
  remotePassword=$4
  sshNode="$sshCommand root@$node"
  rsync_cmd="/usr/bin/rsync -ratlz --rsh=\"/usr/bin/sshpass -p $remotePassword $sshCommand -l $user\""

  rc=$($sshNode "ls /tmp/mq/MQSeries* >$logsDir/mkdirTmpMq 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echoBig "MQ already exists on $node so skipping copy, you might want to run cleanupRDQM.sh to remove it."
    return $rc
  else
    rc=$($sshNode "$rsync_cmd $remoteUser@$location /tmp/mq >$logsDir/rsync  2>&1; echo \$?")
    if [ $rc == 0 ]
    then
      echo "MQ $mq_level successfully copied to $node"
      return $rc
    else
      echoBig "Couldn't copy MQ $mq_level to $node"
      myExit $rc $logsDir/rsync
      return $rc
    fi
  fi
}

function copyMQToNodeFromLocal {
  node=$1
  local_location=$2

  sshNode="$sshCommand root@$node"

  rc=$($sshNode "ls /tmp/mq/MQSeries* >$logsDir/mkdirTmpMq 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echoBig "MQ already exists on $node so skipping copy, you might want to run cleanupRDQM.sh to remove it."
    return $rc
  else
    scp -r $local_location/* $node:/tmp/mq/ >$logsDir/copyMQToNodeFromLocal 2>&1
    rc=$?
    if [ $rc == 0 ]
    then
      echo "MQ successfully copied from $local_location to $node"
      return $rc
    else
      echoBig "Couldn't copy MQ from $local_location to $node:/tmp/mq"
      myExit $rc $logsDir/copyMQToNodeFromLocal
      return $rc
    fi
  fi
}

function createMQDir {
  node=$1
  rc=$($sshCommand root@$node "ls /tmp/mq >$logsDir/lsTmpMq 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echoBig "/tmp/mq directory already exists on $node"
  else
    rc=$($sshCommand root@$node "mkdir /tmp/mq >$logsDir/mkdirTmpMq 2>&1; echo \$?")
    if [ $rc == 0 ]
    then
      echo "/tmp/mq directory created on $node"
    else
      echoBig "Couldn't create /tmp/mq directory on $node"
      myExit $rc $logsDir
      return $rc
    fi
  fi
}

function installSSHPass {
  node=$1
  rc=$($sshCommand root@$node "yum list installed sshpass >$logsDir/sshpass-installed 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echoBig "sshpass already installed on $node"
  else
    rc=$($sshCommand root@$node "yum -y install sshpass >$logsDir/sshpass-install 2>&1; echo \$?")
    if [ $rc == 0 ]
    then
      echo "sshpass installed successfully on $node"
    else
      echoBig "Couldn't install sshpass on $node"
      myExit $rc $logsDir
      return $rc
    fi
  fi
}

function queueManagersPresent {
  node=$1
  #hello
  rc=$($sshCommand root@$node "dspmq | grep QMNAME >$logsDir/queueManagersPresent 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echoBig "Queue Managers are present on $node!"
    return 1
  else
    echoBig "No Queue Managers are present on $node!"
    return 0
  fi
}

function fixRDQMDeveloperBuild {
  node=$1
  devBuildInstDir=$2

  rc=$($sshCommand root@$node "mkdir -p $devBuildInstDir >$logsDir/mkdirInstDir 2>&1; echo \$?")
  if [ $rc -ne 0 ]
  then
    echoBig "mkdir -p $devBuildInstDir failed on $node!"
    myExit $rc $logsDir/mkdirInstDir
    return 1
  fi

  rc=$($sshCommand root@$node "stat $devBuildInstDir/bin >$logsDir/statBin 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echo "$devBuildInstDir/bin already exists!"
  else
    echo "$devBuildInstDir/bin doesn't exist! Linking to /opt/mqm/bin"
    rc=$($sshCommand root@$node "ln -s /opt/mqm/bin $devBuildInstDir/bin >$logsDir/ln-s 2>&1; echo \$?")
    if [ $rc -ne 0 ]
    then
      echoBig "ln -s /opt/mqm/bin $devBuildInstDir/bin failed on $node!"
      myExit $rc $logsDir/ln-s
      return 1
    fi
  fi

  rc=$($sshCommand root@$node "stat $devBuildInstDir/devlib >$logsDir/statLib 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echo "$devBuildInstDir/lib already exists!"
  else
    echo "$devBuildInstDir/lib doesn't exist! Linking to /opt/mqm/lib"
    rc=$($sshCommand root@$node "ln -s /opt/mqm/lib $devBuildInstDir/devlib >>$logsDir/ln-s 2>&1; echo \$?")
    if [ $rc -ne 0 ]
    then
      echoBig "ln -s /opt/mqm/bin $devBuildInstDir/devlib failed on $node!"
      myExit $rc "$logsDir/ln-s"
      return 1
    fi
  fi

  rc=$($sshCommand root@$node "stat $devBuildInstDir/devlib64 >$logsDir/statLib64 2>&1; echo \$?")
  if [ $rc == 0 ]
  then
    echo "$devBuildInstDir/lib64 already exists!"
  else
    echo "$devBuildInstDir/lib64 doesn't exist! Linking to /opt/mqm/lib"
    rc=$($sshCommand root@$node "ln -s /opt/mqm/lib64 $devBuildInstDir/devlib64 >>$logsDir/ln-s 2>&1; echo \$?")
    if [ $rc -ne 0 ]
    then
      echoBig "ln -s /opt/mqm/bin $devBuildInstDir/devlib64 failed on $node!"
      myExit $rc "$logsDir/ln-s"
      return 1
    fi
  fi

  environment="MQ_OVERRIDE_INSTALLATION_PATH=/opt/mqm
MQSPATH=/opt/mqm/bin"
  environment="export MQ_OVERRIDE_INSTALLATION_PATH=/opt/mqm
export MQSPATH=/opt/mqm/bin"

  rc=$($sshCommand root@$node "echo \"$environment\" | tee -a ~/.bashrc /home/mqm/.bashrc >/dev/null 2>&1; echo \$?")
  if [ $rc -ne 0 ]
  then
    echoBig "echo \"export MQ_OVERRIDE_INSTALLATION_PATH=/opt/mqm; export MQSPATH=/opt/mqm/bin\" >> ~/.bashrc failed on $node!"
    return 1
  fi

  rc=$($sshCommand root@$node "echo \"$environment\" | tee -a ~/.ssh/environment /home/mqm/.ssh/environment >/dev/null 2>&1; echo \$?")
  if [ $rc -ne 0 ]
  then
    echoBig "echo \"export MQ_OVERRIDE_INSTALLATION_PATH=/opt/mqm; export MQSPATH=/opt/mqm/bin\" >> ~/.bashrc failed on $node!"
    return 1
  fi

  rc=$($sshCommand root@$node "echo 'Defaults    env_keep += \"MQ_OVERRIDE_INSTALLATION_PATH MQSPATH\"' >> /etc/sudoers; echo \$?")
  if [ $rc -ne 0 ]
  then
    echoBig "echo \"export MQ_OVERRIDE_INSTALLATION_PATH=/opt/mqm; export MQSPATH=/opt/mqm/bin\" >> ~/.bashrc failed on $node!"
    return 1
  fi

  rc=$($sshCommand root@$node "echo \"PermitUserEnvironment yes\" >> /etc/ssh/sshd_config; echo \$?")
  if [ $rc -ne 0 ]
  then
    echoBig "echo \"PermitUserEnvironment yes\" > /etc/ssh/sshd_config failed on $node!"
    return 1
  fi

  rc=$($sshCommand root@$node "systemctl restart sshd > $logsDir/restartSSHd 2>&1; echo \$?")
  if [ $rc -ne 0 ]
  then
    echoBig "systemctl restart sshd failed on $node!"
    return 1
  fi

  echoBig "Developer RDQM Setup complete"

  return 0
}

function endAllQMsOnNode {
  node=$1
  rc=$($sshCommand root@$node "dspmq | grep Running\) > /dev/null 2>&1; echo \$?")

  if [ $rc != 0 ]
  then
    echoBig "No running QMs on this node! Exiting"
    return 0
  fi

  echoBig "ending QMs on node $node1"
  $sshCommand root@$node "dspmq | awk 'match(\$0, /QMNAME\(([^\)]*)\)/, qm) { system (\"endmqm -p \" qm[1]) }'"
}

function addRemoteKeyToKnownHosts {
  host=$1
  user=$2
  if [ -z "`su $user -c \"ssh-keygen -F $host\"`" ]; then
    echo "Adding $host to known_hosts to avoid having to use StrictHostKeyChecking=no on SSH"
    ssh-keyscan -H $host >> /home/$user/.ssh/known_hosts
  fi
}

