#!/bin/bash

read -p "Userbox full hostname (box231.bluehost.com): " box;
shortbox=$(echo $box | cut -d. -f1);
[ -z $shortbox ] && echo "Bad hostname" && exit
/opt/eig_linux/bin/updatelocal
echo
if (grep -q $box /opt/eig_linux/conf/partitions.yaml); then
    echo "Found $box in partitions.yaml, refusing to proceed"
    echo "Please make sure the box is not assigned in backupmaster"
    exit 1;
fi

echo "Cleaning fstab"
sed -i "/$box/d"  /etc/fstab
echo "Cleaning exports"
sed -i "/$box/d"  /etc/exports
echo "Exporting FS"
exportfs -ra

if (grep -qiE '^\s*type[ =:]*zfs$' /opt/eig_linux/conf/backup_server.conf); then
    slices=$(zfs list | grep -Po "^backups\/$shortbox\.\d?e")
    echo -e "WARNING: The following zfs slices will be deleted permanently:\n$slices"
    read -p "Proceed? (y/n) " confirm 
    if [[ $confirm =~ ^[Yy]$ ]]; then
        for slice in $(echo $slices); do 
            zfs destroy $slice
        done
    else
        exit
    fi
else
    lvs=$(lvs | awk "match(\$1,/$shortbox\.[1-9]?e/) {print \$1}") 
    echo -e "WARNING: The following lvs will be deleted permanently:\n$lvs"
    read -p "Proceed? (y/n) " confirm 
    if [[ $confirm =~ ^[Yy]$ ]]; then
        for lv in $(echo $lvs); do
            umount -v /dev/mapper/backup-$lv
            lvremove -f backup/$lv
        done
    else
        exit
    fi
fi
