#!/bin/bash
# Default Values

help_msg () {
    printf """
usage: $0 [-h] [-w|--wait_for_nobackfill WAIT] [-m|--max_backfill BACKFILL] OSDID OSDID ...

Description

  -h, --help              show this help message and exit
  -w WAIT, --wait_for_nobackfill WAIT
                          Wait to start until the cluster has no more backfill
  -m MAX_REMAPPED, --max_remapped MAX_REMAPPED
                          Max remapped PGs
"""
}

BACKFILL=60
while [ $# -gt 4 ] ; do
    key="$1"
    case $key in
        -h|--help)
            help_msg
            exit 0
            ;;
        -w|--wait_for_nobackfill)
            WAIT=1
            shift
            ;;
        -m|--max_remapped)
            BACKFILL="$2"
            shift
            shift
            ;;
        *)
            echo "Arg not found : '$key'"
            exit 1
    esac
done
get_current_remappedg() {
  # Get Current Remapped
  ceph -s -f json | jq '.["osdmap"]["osdmap"]["num_remapped_pgs"]'
}

wait_backfill() {
  backfill=$(get_current_remapped)
  while [ $backfill -gt $1 ]
  do
    backfill=$(get_current_remapped)
    printf "\r Waiting for remapped pgs<${1} -> actually ${backfill}"
    sleep 10
  done
}

if [ ! -z $WAIT ]
then
  wait_backfill 0
fi
echo "Set balancer Off"
ceph balancer off

$OSDLIST=$(systemctl list-units | grep ceph-osd |grep -e ".service    "| awk '{print $1}')
for i in $OSDLIST
do
  wait_backfill $BACKFILL
  echo "Set osd.${i} IN"
  systemctl stop $i
  sleep 10
done

wait_backfill 0
echo "Set balancer On"
ceph balancer on
