#!/bin/bash

ec2_get_all_disks() {
  BDMURL=http://169.254.169.254/latest/meta-data/block-device-mapping/

  curl -s "$BDMURL" | grep ebs | while read -r EBS;do
    DEV=`curl -s "$BDMURL$EBS"`
    if [ -e "/dev/$DEV" ];then
      echo "/dev/$DEV"
    elif [ -e "/dev/xv${DEV#s}" ];then
      echo "/dev/xv${DEV#s}"
    fi
  done
}

disk_needs_init() {
  LABEL=`lsblk "$1" -o LABEL -r -n`
  # if LABEL starts with ebs
  if [ x"${LABEL#ebs}" != x"$LABEL" ];then
    return 1
  fi
  return 0
}

disk_needs_init_lvm() {
  if pvs "$1" > /dev/null 2>&1;then
    return 1
  fi
  return 0
}

disk_mounted() {
  lsblk "$1" -o MOUNTPOINT,TYPE -r -n 2>/dev/null |grep -vE ' lvm$'|cut -d' ' -f 1|grep -q .
}

vg_of_pg() {
  pvs --separator , --noheadings --nosuffix --unit b "$1" |tr -d ' ' | cut -d, -f2
}

vgexists() {
  vgs "$1" >/dev/null 2>&1
}

vgcreate_or_extend() {
  # $1 = vg name
  # $2 = pv to add
  if vgs "$1" >/dev/null 2>&1;then
    vgextend "$1" "$2"
  else
    vgcreate "$1" "$2"
  fi
}

vgfree() {
  if vgexists "$1" ;then
    RET=`vgs --separator , --noheadings --nosuffix --unit b ebs "$1" |tr -d ' ' |cut -d, -f 7 | tr -dc 0-9`
    if [ x"$RET" = x ];then
      echo 0
    else
      echo "$RET"
    fi
  else
    echo 0
  fi
}

ec2_get_all_disks | while read -r REPLY;do
  disk_mounted "$REPLY" && umount "$REPLY"
  #disk_needs_init "$REPLY" && mkfs.ext4 -E nodiscard -q "$REPLY"
  if disk_needs_init_lvm "$REPLY"; then
    pvcreate -f "$REPLY"
    vgcreate_or_extend ebs "$REPLY"
  fi
  echo $REPLY
done

VGFREE="`vgfree ebs`"

if [ "$VGFREE" -gt 0 ];then
  if [ -b /dev/ebs/ebs ];then
    lvresize -L +"$VGFREE"b ebs/ebs
    resize2fs /dev/ebs/ebs
  else
    lvcreate -n ebs -L "$VGFREE"b ebs
    mkfs.ext4 -L ebs /dev/ebs/ebs
  fi
fi

findmnt -S LABEL=ebs > /dev/null 2>&1 || mount -L ebs /srv || true
