#!/bin/bash
set -e
source beegfs-sp

backup_quota_storage_pool() {
  STORAGE_POOL_ID=$1

  local STORAGE_POOL_PARA
  local STORAGE_POOL_ECHO
  if [ -z "$STORAGE_POOL_ID" ]
  then
    STORAGE_POOL_PARA=""
    STORAGE_POOL_ECHO=""
  else
    STORAGE_POOL_PARA="--storagepoolid=$STORAGE_POOL_ID"
    STORAGE_POOL_ECHO="for storage pool $STORAGE_POOL_ID"
  fi

  #echo "saving default quota $STORAGE_POOL_ECHO..."
  FNAME="quota_default_sp$STORAGE_POOL_ID.csv"
  #Do NOT put $STORAGE_POOL_PARA in quotation marks because this variable can be empty!
  beegfs-ctl --getquota --defaultlimits  $STORAGE_POOL_PARA --csv \
  | grep -v 'storage pool Default' | sed '/^$/d' | tail -n +2 \
  | cut -d, -f1-4 \
  > "$FNAME"
  echo "default quota $STORAGE_POOL_ECHO saved into file '$FNAME'"

  #echo "saving user quota $STORAGE_POOL_ECHO..."
  FNAME="quota_uid_sp$STORAGE_POOL_ID.csv"
  #Do NOT put $STORAGE_POOL_PARA in quotation marks because this variable can be empty!
  beegfs-ctl --getquota --uid --all --withzero --withsystem $STORAGE_POOL_PARA --csv \
  | grep -v 'storage pool Default' | sed '/^$/d' | tail -n +2 \
  | cut -d, -f2,4,6 \
  > "$FNAME"
  echo "user quota $STORAGE_POOL_ECHO saved into file '$FNAME'"

  #echo "saving group quota $STORAGE_POOL_ECHO..."
  FNAME="quota_gid_sp$STORAGE_POOL_ID.csv"
  #Do NOT put $STORAGE_POOL_PARA in quotation marks because this variable can be empty!
  beegfs-ctl --getquota --gid --all --withzero --withsystem $STORAGE_POOL_PARA --csv \
  | grep -v 'storage pool Default' | sed '/^$/d' | tail -n +2 \
  | cut -d, -f2,4,6 \
  > "$FNAME"
  echo "group quota $STORAGE_POOL_ECHO saved into file '$FNAME'"
  echo ""
}



main_backup(){
  get_storage_pools

  if $POOLS_EXIST
  then
    echo "Found existing storage pool IDs:"
    for INDEX in ${!POOL_ID_ARRAY[*]}
    do
      echo "${POOL_ID_ARRAY[$INDEX]}"
    done
    echo ""

    for INDEX in ${!POOL_ID_ARRAY[*]}
    do
      echo "processing data for storage pool ID ${POOL_ID_ARRAY[$INDEX]}"
      backup_quota_storage_pool "${POOL_ID_ARRAY[$INDEX]}"
    done
  else
    backup_quota_storage_pool
  fi

}

main_backup

