#!/bin/bash
#set -x 
source /usr/share/ceph-tools/_ct-common


help_msg () {
    printf """
usage: $0 [-h] [-s|--step Step] $CT_HELP_DESCR POOL NEW_PG_NUM 
 
Description         Gradually increase the number of PG_NUM without overloading the cluster
 
Optional
$CT_HELP_MSG
  -s STEP, --step STEP  
                    Increasing PG_NUM by 'Step', minimum and default: 64, if possible power of 2

Positional
  POOL              Pool to apply
  NEW_PG_NUM        New PG_NUM for pool 'POOL', minimum: 64 and Power of 2

Example
  $0 $CT_HELP_EXAMPLE -s 64 Cinder 8192
"""
}

REBALANCING_STEP=64

ct_help_min $# 2
ct_help $@
shift $?
while [ $# -ge 2 ]; do
    key="$1"
    case $key in
        -s|--step)
            if [ $2 -lt 64 ]; then
                echo "Step minimum 64 !"
                ct_on_exit 1
            else
                REBALANCING_STEP=$2
            fi
            shift 2
            ;;
        *)
            POOL=$1
            if [[ ! $(($2 & ($2-1))) == 0 ]]; then
                echo "NEW_PG_NUM must be a power of 2" 
                ct_on_exit 1
            else
                NEW_PG_NUM=$2
            fi
            break
            ;;
    esac
done

get_current_pg_num() {
    # Get Current PG_NUM
    pg=$(ceph osd pool get $POOL pg_num|awk '{print $2}')
    echo $pg
}


CURRENT_PG_NUM=$(get_current_pg_num)

if [ $CURRENT_PG_NUM -ge $NEW_PG_NUM ]; then
# If CURRENT_PG_NUM >= NEW_PG_NUM
  echo No change
  ct_on_exit 0
fi

for count in $(seq $((CURRENT_PG_NUM + REBALANCING_STEP)) $REBALANCING_STEP $NEW_PG_NUM); do
# Increase by REBALANCING_STEP
  ct_healthy_wait $REBALANCING_STEP
  ceph osd pool set $POOL pg_num $count
  ceph osd pool set $POOL pgp_num $count
  sleep 30
done

if [ $CURRENT_PG_NUM -lt $NEW_PG_NUM ]; then
# CURRENT_PG_NUM < NEW_PG_NUM
  ceph osd pool set $POOL pg_num $NEW_PG_NUM
  ceph osd pool set $POOL pgp_num $NEW_PG_NUM
  sleep 30
fi

ct_healthy_wait 0
echo PG_NUM for pool ${POOL} is set to ${NEW_PG_NUM}

ct_on_exit 0
