#!/bin/bash

# This script checks partitions if they have space that can be reclaimed, and if so recalculate the new partition to 80-90% usage
if [ "$1" = "help" ]; then
    echo -e "Command line options:\n\t$0\n\t$0 <force>\n\nDescription\n\tThis script will shrink down LVs to approximately 80% usage to make room on the backup server.\n\tScript can be run with force option to not be promted do complete the resize"
    exit;
fi

#if mountpoint -q /mnt; then
#    echo "/mnt is mounted. Check Failed.  This may mean that a partition shrink is already running. Check why /mnt is mounted.  Program exiting......."
#    exit
#fi

# Get the total and available space on the backup VG, then round our values to the closest integer
VGS_AVAIL=$(vgs backup --noheadings --units g| awk '{print $7}')
VGS_AVAIL_ROUNDED=$(echo $VGS_AVAIL | awk '{print int($1+0.5)}')
VGS_TOTAL=$(vgs backup --noheadings --units g| awk '{print $6}')
VGS_TOTAL_ROUNDED=$(echo $VGS_TOTAL | awk '{print int($1+0.5)}')

echo -e "Starting Space Check...";
echo -e "Current free space on Backup Server is $VGS_AVAIL_ROUNDED GB\n";
read -e -p "Enter a Hostname [Example: box999.bluehost.com] " HOST;
echo
# Check if HOST volumes are single home or multi home
HOME_COUNT=$(df -h /home/$HOST/backup* | grep '/home/' | wc -l)
# If single home, explicity set our home device name
# If multi home, prompt user for the parition number we want to resize
PARTNUM=""
if [ $HOME_COUNT -eq 1 ]; then
    DEV="/home/$HOST/backup"
else 
    echo -e "df output\n\n"
    df -hPB G /home/$HOST/backup[1,2,3,4,5,6,7,8,9,10]
    echo -e "\n\n"
    read -e -p "Enter what backup partition number to resize: " PARTNUM;
    DEV="/home/$HOST/backup$PARTNUM"
    
fi
LV_NAME=$(df $DEV | grep '/mapper/')

# Find if partition is less than 70% used, if not exit script
PER_USED=$(df -h $DEV | grep '/home/' | awk '0+$4 <= 70 {print $4}' | cut -d'%' -f1)
if [ -z $PER_USED ]; then
    echo "$DEV has greater than 70% usage. Can't resize, exiting script"
    exit;
fi


# Get the total and space used in kilobytes for device
TOTAL_SIZE=$(df $DEV | grep '/home/' | awk '{print $1}');
USED_SIZE=$(df $DEV | grep '/home/' | awk '{print $2}');
# Convert to megabytes
MEG_TOTAL=$(echo $(( $TOTAL_SIZE / 1024 )))
MEG_USED=$(echo $(( $USED_SIZE / 1024 )))
# Convert to gigabytes
GIG_TOTAL=$(echo $(( $MEG_TOTAL / 1024 )))
GIG_USED=$(echo $(( $MEG_USED / 1024 )))
# Covert to terabytes
TERA=$(echo $(( $GIG_TOTAL / 1024 )))
TERA_ROUNDED=$(echo $TERA |  awk '{print int($1+0.5)}')
# Get 130% of the gigs used to calculate new parition size
NEWPART=$(echo $(( $GIG_USED * 13 / 10 )))

echo "Original space of partition in GB"
echo "Total Space: $GIG_TOTAL GB "
echo "Acual Space Used: $GIG_USED GB "
echo -e "New Partition Size: $NEWPART GB"
PER_FREE=$(echo $(( 100 - $PER_USED )))
RECLAIM=$(echo $(( GIG_TOTAL - NEWPART )))
echo -e "Space that can be reclaimed $RECLAIM GB" 

#Protect against small partitions being resized
if [ $GIG_USED -lt 200 ]; then
	echo -e "Partition Size exceeds the lower limit for resizing.  Exiting Program......"
	exit
fi

# If our new partition is greater than the available space on our LV, then exit the script
if [ $VGS_AVAIL_ROUNDED -lt $NEWPART ]; then
    echo -e "\nNot enough available space in our VG. Exiting script\n"
    exit
fi

#This sub starts the screen and will rsycn, rename the lv's and tune the partition labels
LV_CREATE_SETUP() {
    SUBDOMAIN=$(echo $HOST | cut -d '.' -f1);
    screen -S ${SUBDOMAIN}.backup${PARTNUM}_shrink -d -m bash -c "touch /opt/eig_linux/bin/partition_shrink_${SUBDOMAIN}.${PARTNUM}e.lock; lvcreate -L ${NEWPART}G -n ${SUBDOMAIN}.${PARTNUM}e.new backup; echo 'Formatting new LV'; mkfs.ext4 ${LV_NAME}.new; echo 'Mounting new LV'; mount ${LV_NAME}.new /mnt; echo 'Starting Rsync. This will take some time to complete.'; rsync -aHXpEogt ${DEV}/ /mnt/; echo 'unmounting temporary mount'; umount /mnt; echo 'running exportfs'; sed -i \"s|^${DEV}|#${DEV}|g\" /etc/exports; exportfs -a; umount -l ${DEV}; maint enable ${HOST}; echo 'Renaming LVs'; lvrename backup ${SUBDOMAIN}.${PARTNUM}e ${SUBDOMAIN}.${PARTNUM}e.old; tune2fs -L ${SUBDOMAIN}.${PARTNUM}e.old /dev/backup/${SUBDOMAIN}.${PARTNUM}e.old; lvrename backup ${SUBDOMAIN}.${PARTNUM}e.new ${SUBDOMAIN}.${PARTNUM}e; tune2fs -L ${SUBDOMAIN}.${PARTNUM}e /dev/backup/${SUBDOMAIN}.${PARTNUM}e; echo 'Removing comments from exports'; sed -i 's/^#//g' /etc/exports; exportfs -a; mount ${LV_NAME} ${DEV}; maint disable ${HOST}; rm -f /opt/eig_linux/bin/partition_shrink_${SUBDOMAIN}.${PARTNUM}e.lock; echo -e \"Partition resize complete for $HOST. One you have confirmed the data moved correctly, remove the old LV:\nlvremove ${LV_NAME}.old\n\";"
    echo -e "\nScreen session has been started for resize. Attach to screen to see status:\nscreen -x ${SUBDOMAIN}.backup${PARTNUM}_shrink"
}

# Check if we want the resize to happen or if force option was passed on command line
if [ "$1" = "force" ] ; then
    LV_CREATE_SETUP
else
    echo
    read -e -p "Do you want to continue with the resize? (Y|N) " RESIZE_RESPONSE
    if [ $RESIZE_RESPONSE = "y" ] || [ $RESIZE_RESPONSE = "Y" ] || [ $RESIZE_RESPONSE = "yes" ] ; then
        LV_CREATE_SETUP
    else
        echo -e "\nNot doing resize. Exiting script\n"
        exit
    fi
fi
