#!/bin/bash
# License: GPL 
# Author: Steven Shiau <steven _at_ nchc org tw>
# Description: Program to assign a friendly davfs2 setting for uploading Clonezilla image:
# It will modify the following parameters in /etc/davfs2/davfs2.conf and /etc/drbl/drbl-ocs.conf. This will only be done in DRBL/Clonezilla live env.
# For davfs2.conf:
# ===============
# buf_size 10240 #KiByte maybe more
# use_locks 0
# use_expect100 1
# use_compression 1
# cache_size 64 #MiByte maybe more, dynamic
# delay_upload 0
# ===============
# For drbl-ocs.conf:
# ===============
# VOL_LIMIT_DEFAULT="1000000"
# VOL_LIMIT_IN_INTERACTIVE="4096"
# ===============

DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"
. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. /etc/drbl/drbl-ocs.conf
. $DRBL_SCRIPT_PATH/sbin/ocs-functions

# Settings:
dav_conf="/etc/davfs2/davfs2.conf"
davfs2_params="buf_size use_locks use_expect100 use_compression cache_size delay_upload"

# Functions
get_davfs2_cache_size() {
  cache_d_line="$(LC_ALL=C grep -q -E "^[[:space:]]*cache_dir" /etc/davfs2/davfs2.conf)"
  if [ -n "$cache_d" ]; then
    cache_d="$(LC_ALL=C echo $cache_d_line | awk -F" " '{print $2}')"
  else
    cache_d="/var/cache/davfs2"
  fi
  free_dsk_space="$(LC_ALL=C df -BM $cache_d | tail -n 1 | awk -F" " '{print $4}')"
  # We set the cache size as 20% of the system.
  cache_size="$(LC_ALL=C echo "scale=0; "${free_dsk_space%M}" * 1.0 / 5" | bc -l)"
  echo "$cache_size"
} # end of get_davfs2_cache_size

############
### MAIN ###
############

# If it's not in DRBL/Clonezilla live env, exit.
if ! is_drbl_clonezilla_live_env; then
  exit 1
fi
davfs2_cache_size="$(get_davfs2_cache_size)"  # MiByte
[ -z "$davfs2_cache_size" ] && davfs2_cache_size="$davfs2_cache_size_def"
# volume size in drbl-ocs.conf has to be adjusted, too.
perl -pi -e "s/VOL_LIMIT_DEFAULT=.*/VOL_LIMIT_DEFAULT=$davfs2_cache_size # Modified by prep-ocsroot for davfs2/" /etc/drbl/drbl-ocs.conf
perl -pi -e "s/VOL_LIMIT_IN_INTERACTIVE=.*/VOL_LIMIT_IN_INTERACTIVE=$davfs2_cache_size # Modified by prep-ocsroot for davfs2/" /etc/drbl/drbl-ocs.conf

echo "Tuning davfs2 parameters in $dav_conf..."
for id in $davfs2_params; do
  eval rid=\$davfs2_$id
  if grep -q -E "^$id[[:space:]]+" $dav_conf; then
    # found the old one, replace that	  
    perl -pi -e "s|^$id\s.*|$id $rid|g" $dav_conf
  else
    # old one does not exist, create one
    cat <<-EOF >> $dav_conf
$id $rid
EOF
  fi
done
