#!/bin/bash
#set -x 

help_msg () {
    printf """
usage: $0 [-h] [-b|--backfilling Max_backfilling] Hosts
 
Description               Gradually increase the number of PG_NUM without overloading the cluster
 
Optional
  -h, --help              show this help message and exit
  -M Max_remapped, --max_remapped Max_remapped            
                          Increasing PG_NUM waits until there is less 'Max_remapped' in progress to resume, default: 4
  -p Prefix, --prefix
                          Prefix off Host
Positional
  HOSTS                   List of Hosts (must be equal to 3)
"""
}

declare -a Z1
declare -a Z2
declare -a Z3

MAX_BACKFILLING=1

if [ $# -lt 2 ]
then
    help_msg
    exit 1
fi

get_osd_by_host() {
  _OSDS=$(ceph osd status ${1} | grep "new" | awk '{print $2}')
  for OSD in $_OSDS
  do
    OSDS="${OSDS} $OSD"
  done
  echo $OSDS
}

PREFIX="bdb2-cephosd-"
while [ $# -ge 3 ]; do
    key="$1"
    case $key in
        -h|--help)
            help_msg
            exit 0
            ;;
        -M|--max_remapped)
            MAX_BACKFILLING=$2
            shift
            shift
            ;;
        -p|--prefix)
            PREFIX=$2
            shift
            shift
            ;;
        *)
            if [ $# -ne 3 ]
            then
              echo "The number of hosts must be equal to 3"
              exit 1
            fi
            Z1=($(get_osd_by_host ${PREFIX}${1}))
            Z2=($(get_osd_by_host ${PREFIX}${2}))
            Z3=($(get_osd_by_host ${PREFIX}${3}))
            break
            ;;
    esac
done

echo ${1}: adding OSDs ${Z1[@]}
echo ${2}: adding OSDs ${Z2[@]}
echo ${3}: adding OSDs ${Z3[@]}

get_current_backfilling() {
  # Get Current Remapped
  ceph -s -f json | jq '.["osdmap"]["osdmap"]["num_remapped_pgs"]'
}

test_osd_down() {
  # Test if a OSD is down
  num=0
  if [ $(ceph osd tree down | wc -l) -gt 1 ] ; then
    echo OSD Down, stop adding OSD !
    exit 1
  fi
}

healthy_wait() {
  # Wait for Backfilling <= MAX_BACKFILLING
  cbf=$(get_current_backfilling)
  while [ $cbf -gt $MAX_BACKFILLING ]; do
    test_osd_down
    printf "\r$(ceph -s | grep 'remapped pgs')                            "
    cbf=$(get_current_backfilling)
    sleep 1
  done
  printf "\r                                                                                              \r"
}

for o in ${!Z1[@]}; do
  healthy_wait
  ID=${Z1[${o}]}
  ceph osd in $ID
  sleep 5
  ID=${Z2[${o}]}
  ceph osd in $ID
  sleep 5
  ID=${Z3[${o}]}
  ceph osd in $ID
  sleep 20
done
healthy_wait
echo End adding OSDs for hosts $@
