#!/bin/bash

box=$1;
if ( [ -z $box ] ); then
        read -p "Userbox full hostname (box231.bluehost.com): " box;
fi
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 "^backup\/$shortbox[a-z]?\.\d?e"))
    slices_final=()
    for slice in ${slices[@]}; do
       grep -q $slice /opt/eig_linux/conf/partitions.yaml || slices_final+=($slice)
    done
    echo -e "WARNING: The following zfs slices will be deleted permanently:\n${slices_final[@]}"
    read -p "Proceed? (y/n) " confirm 
    if [[ $confirm =~ ^[Yy]$ ]]; then
        for slice in ${slices_final[@]}; do 
            zfs destroy $slice
        done
    else
        exit
    fi
else
    lvs=($(lvs | awk "match(\$1,/$shortbox[a-z]?\.[1-9]?e/) {print \$1}"))
    lvs_final=()
    for lv in ${lvs[@]}; do
       grep -q $lv /opt/eig_linux/conf/partitions.yaml || lvs_final+=($lv)
    done
    echo -e "WARNING: The following lvs will be deleted permanently:\n${lvs_final[@]}"
    read -p "Proceed? (y/n) " confirm
    if [[ $confirm =~ ^[Yy]$ ]]; then
        for lv in ${lvs_final[@]}; do
            umount -v /dev/mapper/backup-$lv
            lvremove -f backup/$lv
        done
    else
        exit
    fi
fi
