#!/bin/bash

mpc stop
umount /var/lib/mpd/music/NAS

LOG=/var/lib/mpd/music/RAM/.nas_setting.log

# work dir
dst=/tmp/cifsdst
mkdir $dst

# detect protocol
user=`echo $2 | tr -d " "`
pass=`echo $3 | tr -d " "`
opt="cache=none,iocharset=utf8,username=$user,password=$pass"

echo "updating fstab start!!" > $LOG

hst=`echo $1 | sed -E 's/^\/\/([^/]+).+/\1/g'`

echo " Checking ping reply to ${hst}" >> $LOG

/bin/ping -c 1 -W 1 ${hst} > /dev/null
if [ ! $? = 0 ]; then
  echo "  !!!${hst} has not reply via ipv4" >> $LOG
  echo "  Checking via ipv6" >> $LOG
  /bin/ping6 -c 1 -W 1 ${hst} > /dev/null
  if [ ! $? = 0 ]; then
    echo "  !!!${hst} has not reply via ipv6" >> $LOG
    echo "!!!Aborting the process!!!" >> $LOG
    exit 1
  fi
fi
echo "  Ping successed" >> $LOG
echo "" >> $LOG

echo " Checking cifs security mode and protocol version" >> $LOG
exopt=""
declare -a aver=("1.0" "2.0" "2.1" "3.0")
for e in ${aver[@]}; do
  mount -t cifs $1 $dst -o $opt,sec=ntlm,vers=${e} >/dev/null 2>&1
  if [ $? = 0 ]; then
    exopt=sec\=ntlm,vers\=${e}
    umount $dst
  fi

  mount -t cifs $1 $dst -o $opt,sec=ntlmssp,vers=${e} >/dev/null 2>&1
  if [ $? = 0 ]; then
    exopt=sec\=ntlmssp,vers\=${e}
    umount $dst
  fi
done

if [ "$exopt" = "" ]; then
  echo "  !!!Can not resolve the security mode or protocol version." >> $LOG
  echo "  Aborting the process!!!" >> $LOG
  rmdir $dst
  exit 1
fi

echo "  security mode and protocol version: $exopt" >> $LOG
exopt=,$exopt

sync

# detect best rsize prepare
declare -a arsize=("7300" "16060" "32120" "61320" "129940")

fioconf=/home/pi/misc/fio.conf
testfile=
bestrsize=
bestbw=0
bestctx=1000000

declare -a arsize2=()
declare -a abw=()
declare -a alatency=()
declare -a actx=()
declare -a amajf=()
declare -a aminf=()

mount -t cifs $1 $dst -o $opt,$exopt,wsize=4096 >/dev/null 2>&1
dd of=$dst/rsize_test_dummy bs=4k count=0 seek=2500
sync

umount $dst

echo "" >> $LOG
echo " Checking best rsize" >> $LOG
echo "" >> $LOG
echo "  rsize       BW    CTX  latency" >> $LOG
for e in ${arsize[@]}; do
  mount -t cifs $1 $dst -o ro,$opt,$exopt,rsize=${e} >/dev/null 2>&1

  # fio start
  out=`fio --readonly -filename="$dst/rsize_test_dummy" --output-format=terse $fioconf | cut -d';' -f7,8,16,90,91,92`

  #echo "RSIZE ${e}:$out" >> $LOG

  # detect best rsize
  bw=`echo $out|cut -d';' -f1`
  latency=`echo $out|cut -d';' -f3|cut -d'.' -f1`
  ctx=`echo $out|cut -d';' -f4`
  majf=`echo $out|cut -d';' -f5`
  minf=`echo $out|cut -d';' -f6`

  arsize2+=( ${e} )
  abw+=( $bw )
  alatency+=( $latency )
  actx+=( $ctx )
  amajf+=( $majf )
  aminf+=( $minf )

  printf "%7d %8d %6d %8d\n" ${e} $bw $ctx $latency >> $LOG

  if [ $bw -gt $bestbw ];then
    bestbw=$bw
    bestrsize=${e}
  fi
  sudo umount $dst
done

i=0
#echo "rsize  bw  lat  ctx  majf  minf" >> $LOG
for e in ${arsize2[@]}; do
  count=0
  for ((ibw = 0; ibw < ${#abw[@]}; ibw++)){
    if [ ${abw[i]} -lt ${abw[ibw]} ];then
      let count++
    fi
  }
  if [ $count -lt 3 ];then
    count=0
    for ((ilat = 0; ilat < ${#alatency[@]}; ilat++)){
      if [ ${alatency[i]} -gt ${alatency[ilat]} ];then
        let count++
      fi
    }
    if [ $count -lt 3 ];then
      count=0
      for ((ictx = 0; ictx < ${#actx[@]}; ictx++)){
        if [ ${actx[i]} -gt ${actx[ictx]} ];then
          let count++
        fi
      }
      if [ $count -lt 3 ];then
        if [ "$bestbw" = "" ];then
          bestctx=${actx[i]}
          bestbw=${abw[i]}
          bestrsize=",rsize=${e}"
        elif [ ${actx[i]} -lt $bestctx ];then
          bestctx=${actx[i]}
          bestbw=${abw[i]}
          bestrsize=",rsize=${e}"
        fi
      fi
    fi
  fi
  #echo "${e} ${abw[i]} ${alatency[i]} ${actx[i]} ${amajf[i]} ${aminf[i]}" >> $LOG
  let i++
done

# clean up
mount -t cifs $1 $dst -o $opt,$exopt,rsize=4096 >/dev/null 2>&1
rm "$dst/rsize_test_dummy"
umount $dst
rmdir $dst

# edit fstab
target=/etc/fstab
nas="$1 /var/lib/mpd/music/NAS cifs ro,noauto,x-systemd.automount$exopt$bestrsize,$opt"

echo "" >> $LOG
echo "  best bandwidth : $bestbw kB/sec" >> $LOG
echo "" >> $LOG
echo "  fstab setting  : $nas" >> $LOG

sed -i.bak -e "/# NAS Setting/{n;d}" $target
sed -i -e "/# NAS Setting/a $nas" $target
sync

echo " Restarting mpd and mounting NAS with new setting" >> $LOG

systemctl stop mpd
systemctl daemon-reload
mount -a
systemctl start mpd

mountpoint /var/lib/mpd/music/NAS
ret=$?
echo "" >> $LOG
if [ $? -eq 0 ]; then
  echo "NAS setting successed" >> $LOG
else
  echo "Failed to mount NAS with new setting" >> $LOG
fi
sleep 2
rm $LOG

exit $ret

