#!/bin/bash

LOG_PATH=/tmp/reset_disk.log

# Note: not all disks need to re-part, 
# just the machines that with multi-docker-containers

need_to_part=0

# check multi containers by docker ps -a -q
# but what if docker containers are not running?
# containers=`docker ps -a -q`
# containers=(${containers})
# container_number=${#containers[@]}
# if [[ ${container_number} -gt 1 ]]; then
#   need_to_part=1
# fi

# check multi containers by config files
# but Node-Monitor need to be adapted completely, that needs a lot of time
container_number=`cat /etc/pear/pear_docker/docker_cp_name.conf | awk -F, '{print NF}'`
if [ ${container_number} -gt 1 ]; then
  need_to_part=1
fi

# part disks
if [ ${need_to_part} -eq 1 ]; then
  # check part script file
  script="/etc/pear/pear_scripts/part.sh"
  if [ ! -f ${script} ]; then
    datetime=`date "+%Y-%m-%d %H:%M:%S"`
    echo "${datetime} [FATAL] part script not exist" >> ${LOG_PATH}
    exit 1
  fi
  # check have been parted?
  done_file=/tmp/part_done.txt
  if [ -f ${done_file} ]; then
    datetime=`date "+%Y-%m-%d %H:%M:%S"`
    echo "${datetime} [FATAL] part had already been done" >> ${LOG_PATH}
    exit 1
  fi
  # before part disks, shutdown docker containers 
  containers=`docker ps -a -q`
  containers=($containers)
  container_number=${#containers[@]}
  if [ ${container_number} -gt 1 ]; then
    datetime=`date "+%Y-%m-%d %H:%M:%S"`
    echo "${datetime} [ERROR] shutdown docker containers" >> ${LOG_PATH}
    docker rm -f $(docker ps -a -q)
  fi
  # do parted action
  echo "clean disks..."
  chmod +x ${script} && ${script} --part --mount
  if [ ! -f ${done_file} ]; then
    datetime=`date "+%Y-%m-%d %H:%M:%S"`
    echo "${datetime} [FATAL] clean failed, handle this cleaning stuff manually" >> ${LOG_PATH}
    exit 1
  fi
  ## 
  # config for pear_monitor
  # 
  # disk config
  sata_list="/sata*"
  sata_array=(${sata_list})
  sata_number=${#sata_array[@]}
  if [ ${sata_number} -gt 10 ]; then
    sata_number=10
  fi
  # 
  /usr/sbin/pear_monitor --auto_disk=/sata,0,${sata_number}
  datetime=`date "+%Y-%m-%d %H:%M:%S"`
  echo "${datetime} [INFO ] part success, used sata number: ${sata_number}" >> ${LOG_PATH}
else
  datetime=`date "+%Y-%m-%d %H:%M:%S"`
  echo "${datetime} [INFO ] did not do anything" >> ${LOG_PATH}
fi
