#!/bin/sh
#
# mount samba shares
#
# runlevels: geexbox, debug, configure

if test -x /usr/bin/smbmount -a -f /etc/network; then
  echo "### Mounting Samba shares ###"

mount_smb()
{
  user=$1
  pass=$2
  name=$3
  ip=$4
  shift 4
  while [ $# -gt 0 ]; do
    dir="/mnt/shares/$name/$1"
    if [ ! -e "$dir" ]; then
      mkdir -p "$dir"
      mount "//$ip/$1" "$dir" -t cifs -o "ro,iocharset=utf8,user=$user,pass=$pass" || smbmount "//$name/$1" "$dir" -o "ro,iocharset=utf8,ip=$ip,username=$user,passwd=$pass" || rmdir -p "$dir"
    fi
    shift
  done
}

  (
    . /etc/network
    while [ ! -f /var/ifup ]; do
      sleep 1
    done
    OPT="-N"
    test -n "$SMB_USER" && OPT="-U$SMB_USER%$SMB_PWD"
    saveifs=$IFS
    while true; do
      smbtree "$OPT" | while read mounts; do
      (
        IFS=/
        mount_smb "$SMB_USER" "$SMB_PWD" $mounts
        IFS=$saveifs
      )&
      done
      for STATIC_SMB in `sed -n "s/^STATIC_SMB=\"\(.*\)\"/\1/p" /etc/network`; do
      (
        USER=`echo $STATIC_SMB | sed "s/<%>.*//"`
        PASS=`echo $STATIC_SMB | sed -e "s/.*<%>//" -e "s/<@>.*//"`
        IP=`echo $STATIC_SMB | sed -e "s/.*<@>//" -e "s/<&>.*//"`
        NAME=`echo $STATIC_SMB | sed -e "s/.*<&>//" -e "s/<#>.*//"`
        MOUNTS="`echo $STATIC_SMB | sed "s/.*$NAME<#>//" | sed "s/<#>/ /g"`"
        mount_smb "$USER" "$PASS" "$NAME" "$IP" $MOUNTS
      )&
      done
      [ -z "$NET_RESCAN_DELAY" -o $NET_RESCAN_DELAY -le 0 ] && break
      sleep $NET_RESCAN_DELAY
    done
  )>/dev/null 2>&1 &
fi

exit 0
