#!/bin/bash

storages=($(jq -rM .storage[] /etc/pear/pear_monitor/config.json))
swap_path=''
maximum_storage=''

find_maximum_storage() {
   for dir in "${storages[@]}"; do
      if [ "${1}1" = "${dir}1" ]; then
         continue
      fi
      storage_size=$(df "${dir}" 2>/dev/null | awk 'NR==2 {print $2}')
      if [ -z "${Maximum_storage}" ]; then
         maximum_storage="${dir}"
         maximum_storage_size="${storage_size}"
      else
         if [ "${storage_size}" -gt "${maximum_storage_size}" ]; then
            maximum_storage="${dir}"
            maximum_storage_size="${storage_size}"
         fi
      fi
   done
   swap_path="${maximum_storage}/"
}

select_storage() {
   if [ ${#storages[@]} -eq "0" ]; then
   echo "Read storages from config.json failed"
   exit 1
   fi
   for dir in "${storages[@]}"; do
      if [ "$(df "${dir}" 2>/dev/null | awk 'NR==2' | wc -l)1" = "11" ] && [ "$(df "${dir}" 2>/dev/null | awk 'NR==2 {print $6}')1" = "/1" ]; then
         echo "${dir} is in system disk"
         if [ ${#storages[@]} -eq "1" ]; then
            swap_path="/"
            break
         elif [ ${#storages[@]} -gt 1 ]; then
            find_maximum_storage "${dir}"
            break
         fi
      fi
   done
   if [ -z "${swap_path}" ]; then
      swap_path="/"
   fi
}


flag=`cat /proc/swaps | grep pear_swap | wc -l`
if [ "${flag}" -eq "0" ];then
   select_storage
   cd ${swap_path}
   dd if=/dev/zero of=pear_swap bs=1G count=$1
   mkswap pear_swap
   chmod 0600 pear_swap
   swapon "${swap_path}pear_swap"

   cat /etc/fstab | grep -v pear_swap > /tmp/fstab
   install -m 644 /tmp/fstab /etc/fstab
   echo "${swap_path}pear_swap swap swap defaults 0 0" >> /etc/fstab

   # num=`cat /etc/fstab |grep pear_swap |wc -l`
   # if [ "${num}" -lt "1" ];then
   #    echo /pear_swap swap swap defaults 0 0 >> /etc/fstab
   # fi
fi
#swapoff /pear_swap
#rm -rf /pear_swap

exit 0
 