#!/bin/bash

# Script to deploy on an instance that has an ephemeral volume as /dev/nvme0n1 (adjust env var PARTITION if different)
# Ensures the partition is xfs-formatted, any existing partition contents will be overwritten if formatted otherwise.
# An existing xfs partition will be left alone.
METADATA=$( ec2-metadata -d | sed -e 's/^user-data: //' )
echo "Metadata: ${METADATA}"
if echo "${METADATA}" | grep -q "^image-upgrade$"; then
  echo "Image upgrade; not trying to mount/format ephemeral volume"
  exit 0
else
  echo "No image upgrade; looking for ephemeral volume and trying to format with xfs..."
  . imageupgrade_functions.sh
  PARTITION_NAME=$(identify_suitable_partition_for_ephemeral_volume)
  if [[ -n "${PARTITION_NAME}" ]]; then
    PARTITION=/dev/${PARTITION_NAME}
    if awk '{print $1;}' /proc/mounts | grep "${PARTITION}"; then
        echo "Partition ${PARTITION} already mounted; not formatting/mounting ephemeral volume"
    else
        FSTYPE=$(blkid -p $PARTITION -s TYPE -o value)
        if [[ "$FSTYPE" != "xfs" ]]; then
            echo FSTYPE was "$FSTYPE" but should have been xfs. Formatting $PARTITION...
            mkfs.xfs -f $PARTITION
        else
            echo FSTYPE was "$FSTYPE" which is just right :-\)
        fi
        # mount the thing to /var/lib/mongo
        mount $PARTITION /var/lib/mongo
        chown mongod:mongod /var/lib/mongo # Added for robustness
    fi
  fi
fi
