#!/bin/bash
#
#

cloud-init-per once msoc_ebs_vols sudo bash - << 'OUTEREOF'
SUDO=""

function get_nvme_device {
  local DEVICE=$1
  # Iterate over all the nvme devices, looking for those in /dev
  for blkdev in $( sudo nvme list | awk '/^\/dev/ {print $1 }' ); do
    # For each device grab the desired device name from the vendor data
    mapping=$(nvme id-ctrl --raw-binary "${blkdev}" 2>/dev/null | cut -c3073-3104 | sed 's/ //g' | sed 's#/dev/##g' )
    # If the desired device name is one of those currently requested
    if `echo $DEVICE | egrep -q "\<${mapping}\>"`; then
      # Repoint our device variable to the real device
      echo $blkdev
      return
    fi
  done
  echo ${DEVICE}_NOTFOUND
}

function do_the_mount
{
  # Mount BLOCK_DEV at MOUNTPOINT, creating the directory if necessary
  # and formatting the filesystem.
	VOL_LABEL=$1
	BLOCK_DEV=$2
	MOUNTPOINT=$3

  # We're going to loop up to 6 times, looking for the NVME device
  # that matches block_dev, sleeping 30 seconds between attempts,
  # to give the attachment time to take place.
  LIMIT=6
  device=$( get_nvme_device ${BLOCK_DEV} )
  >&2 echo Looking for $device
  while [[ $LIMIT -gt 0 && ! -e $device ]]; do
          sleep 30
          device=$( get_nvme_device ${BLOCK_DEV} )
            >&2 echo Looking for $device
          LIMIT=$(( $LIMIT - 1 ))
  done

	if ! [[ -d ${MOUNTPOINT} ]]; then
		${SUDO} mkdir -p ${MOUNTPOINT}
	fi

	if ! ${SUDO} blkid -l -t LABEL=${VOL_LABEL}; then
		${SUDO} mkfs.xfs -L ${VOL_LABEL} ${device}
		${SUDO} mount LABEL=${VOL_LABEL} ${MOUNTPOINT}
	fi

	if ! egrep "LABEL=${VOL_LABEL}" /etc/fstab; then
		${SUDO} bash -c "cat >> /etc/fstab" <<EOF
LABEL=${VOL_LABEL}       ${MOUNTPOINT}    xfs    defaults  0 2
EOF
	fi

	if ! egrep " ${MOUNTPOINT} " /proc/mounts; then
		${SUDO} mount ${MOUNTPOINT}
	fi
}

do_the_mount repo_vol xvdf /var/www/html


OUTEREOF
