#!/bin/bash
export STY=1
Log_file=/opt/nf-observability/remediations/logs
THRESHOLD=98
vm_running=$(virsh list --all | grep instance | grep running > /dev/null ; echo $?)
vm_shutdown=$(virsh list --all | grep instance | grep "shut off" > /dev/null ; echo $?)
vm_id=$(virsh list --all | grep -i instance | awk {'print $1'})

#Logging to syslog
/usr/bin/logger  -t $0 "diskclean auto-remediation initiated on $1"

vm_fstrim() {
if [[ -x /usr/local/bin/fstrim.pl ]]; then
    /usr/local/bin/fstrim.pl > $Log_file/$vm_id-fstrim.log 2>&1 
else
    /usr/bin/virsh domfstrim $vm_id > $Log_file/$vm_id-fstrim.log 2>&1
fi
}

disk_usage() {
USAGE=$(df /var/lib/nova/instances | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$USAGE" -le "$THRESHOLD" ]; then
    echo "/var/lib/nova/instances disk usage is under control: $USAGE%"
else
    echo "Couldn't able to clear much space, Please check the issue manually or escalte it to VHS"
fi
}


if [[ $1 == "/var/lib/nova/instances" && $vm_running == 0 ]];then
    vm_fstrim
    echo "fstrim has been initiated, please check the logs under $Log_file"
    disk_usage
elif [[ $1 == "/var/lib/nova/instances" && $vm_shutdown == 0 ]];then
    vm_uuid=$(virsh dominfo $vm_id | grep UUID: | awk {'print $2'})
    /usr/bin/virt-sparsify --in-place /var/lib/nova/instances/$vm_uuid/disk > $Log_file/$vm_uuid-spacify.log 2>&1 
    echo "sparsify command has been initiated, please check the logs under $Log_file"
    disk_usage
else
    echo "Either VM is not avaible on the node or on paused state, automation won't work in this case, please invetsigate/escalate the issue "
fi
