#!/bin/bash
#
# Copyright (c) 2022 by cisco Systems, Inc.
# All rights reserved.
#
# September 2022, Aditya Iyengar
#
# Platform: Lindt Only
# This script is used for "show media" CLI. This script accounts
# for partition size reported by "lvs" and "df" command. This
# script can be expanded as new requirements come up.

declare -r PY=python3

# Function to read output from "df" command
get_df_table() {
    FORMAT="%s %s %s %s %s\n"
    df -hlP |                                                                                                           \
        sed `for i in /*: ; do [ -h $i ] && echo \ -e s,$(readlink $i),${i#/},; done` |                                 \
        grep -vE '(overlay|shm|none|Filesys|mnt|run|boot|rootfs|common|tmpfs|devfs|panini.*lv0|cmdline|^run|unionfs)' | \
        sed -e 's,/misc/config,config:,g'               \
            -e 's,/misc/disk1,harddisk:,g'              \
            -e 's,/var/xr/disk1,harddisk:,g'            \
            -e 's,/misc/scratch,disk0:,g'               \
            -e 's,/var/xr/scratch,disk0:,g'             \
            -e 's,/misc/app_host,apphost:,g'            \
            -e 's,/var/log,log:,g'                      \
            -e 's,/$,rootfs:,g' |                       \
        awk '{printf "'"$FORMAT"'",$6,$2,$3,$5,$4}' |   \
        sed -e "s/harddiska:b/harddiskb: /"  # cleanup
}

# Fuction to read output from "lvs" command
get_lvs_table() {
    local lv_list=("install-rootfs-thinpool"            \
                   "install-data-thinpool")

    for lv in ${lv_list[@]}; do
        local lv_short_name=$lv
        # lvs table info
        local lv_name
        local lv_size
        local lv_available
        local lv_used
        local data_percent

        lvs --select lv_name=$lv_short_name --noheadings --units B     \
            -o lv_name,lv_size,data_percent                            \
            2>/dev/null | while read lv_name lv_size data_percent; do  \
                                lv_size=$(echo $lv_size | grep -o -E '[0-9]+')
                                lv_name="$(echo $lv_name | grep -oh 'rootfs\|data'):"
                                lv_used=$($PY -c "print(int(($lv_size*$data_percent)/100))")
                                lv_available=$($PY -c "print(int($lv_size-$lv_used))")
                                data_percent="$($PY -c "print(round($data_percent))")%"
                                lv_size=$(numfmt --to=iec --format=%.1f $lv_size | sed 's/\.0//g')
                                lv_used=$(numfmt --to=iec --format=%.1f $lv_used | sed 's/\.0//g')
                                lv_available=$(numfmt --to=iec --format=%.1f $lv_available | sed 's/\.0//g')
                                echo $lv_name $lv_size $lv_used $data_percent $lv_available
                          done
    done
}

get_lvs_table
get_df_table

