#!/bin/bash

# Disclaimer of Warranty

# The software is provided "as is", without warranty of any kind, express or implied, including
# but not limited to the warranties of merchantability, fitness for a particular purpose and
# noninfringement. In no event shall the authors or copyright holders be liable for any claim,
# damages or other liability, whether in an action of contract, tort or otherwise, arising from,
# out of or in connection with the software or the use or other dealings in the software.

handle_error() {
    echo "Error: $1" >&2
    exit 1
}

for cmd in openstack cinder awk; do
    command -v "$cmd" >/dev/null 2>&1 || handle_error "Required command '$cmd' is not available."
done

# Specify the project ID
if [ -z "$OS_PROJECT_NAME" ]; then
    echo "Please enter the name of the project in form of 'project_xxxxxxx':"
    read -r project_name
else
    project_name=$OS_PROJECT_NAME
fi

project_id=$(openstack project list | awk -v pname="$project_name" \
'$4==pname {print $2}' || handle_error "Failed to retrieve the project ID for \
'$project_name'.")

echo "Available resources in ${project_name} (ID: ${project_id})"

(openstack limits show --absolute | awk '
/maxTotalRAMSize/ {maxram = $4}
/totalRAMUsed/ {usedram = $4}
/maxTotalInstances/ {maxins = $4}
/totalInstancesUsed/ {usedins = $4}
/maxTotalCores/ {maxcpu = $4}
/totalCoresUsed/ {usedcpu = $4}
END { print "    Instances: " maxins - usedins "/" maxins "\n" \
"    vCPUs: " maxcpu - usedcpu "/" maxcpu "\n" \
"    RAM: " maxram - usedram "/" maxram }') || handle_error "Failed to parse \
available computing resources for the '$project_name'."

(cinder quota-usage $project_id 2>&1 | awk '
/snapshots[[:space:]]/ {usedsnap = $4; maxsnap = $8}
/volumes[[:space:]]/ {usedvol = $4; maxvol = $8}
END { print "    Volumes: " maxvol - usedvol "/" maxvol "\n" \
"    Snapshots: " maxsnap - usedsnap "/" maxsnap }') || handle_error \
"Failed to parse available storage resources for the '$project_name'."
