1#!/bin/bash
2
3# smbbind.sh share mountpoint
4# smbbind.sh "//SERVER/SHARE" "/mnt/somewhere"
5
6check_every=30 #Seconds
7timeout_after=5 #Seconds
8restart_after=30 #Seconds
9
10hide_path=~/.smbbind/
11cifs_opts="rw,cache=strict,username=nt_username,password=nt_password,domain=nt_domain,uid=0,noforceuid,gid=0,noforcegid,file_mode=0755,dir_mode=0755,nounix,serverino,rsize=61440,wsize=57344,actimeo=60,_netdev"
12
13share="$1"
14bind_mountpoint="$2"
15
16function clean {
17 #Umount bindfs, next umount cifs, then exit.
18 echo [..] Cleaning...
19 #The only open handle opened on the cifs share should be the bindfs one.
20 echo [..] forcing umounting bindfs on "$bind_mountpoint"
21 kill -9 $bindfs_pid
22 umount -f "$bind_mountpoint"
23 echo [OK] Done.
24 # Umounted bindfs, cifs should umount without problems
25 echo [..] Forcing umounting cifs on "$cifs_mountpoint"
26 umount -f "$cifs_mountpoint"
27 umount -l "$cifs_mountpoint"
28 echo [OK] Done cleaning.
29}
30
31function finish {
32 echo exiting...
33 clean
34 trap exit INT TERM EXIT
35 exit
36}
37
38trap finish INT TERM EXIT
39
40#Prepare environment
41 mkdir $hide_path &>/dev/null
42 cifs_mountpoint=$hide_path/$(echo $bind_mountpoint|tr '/' '_')
43 mkdir -p $cifs_mountpoint &>/dev/null
44 mkdir -p $bind_mountpoint &>/dev/null
45
46while true ; do
47
48 #Mount things:
49 echo [..] mounting cifs "$share" on "$cifs_mountpoint"
50 if timeout 10 mount.cifs "$share" "$cifs_mountpoint" -o $cifs_opts ; then
51 echo [OK] mounted cifs "$share" on "$cifs_mountpoint"
52
53 echo [..] mounting bind "$cifs_mountpoint" on "$bind_mountpoint"
54 bindfs "$cifs_mountpoint" "$bind_mountpoint"
55 #Getting the pid of bindfs is tricky.
56 bindfs_pid=$(ps -eo pid,args|grep bindfs |grep "$cifs_mountpoint" |grep "$bind_mountpoint" |cut -d " " -f 1)
57 echo [OK] mounted bind "$cifs_mountpoint" on "$bind_mountpoint"
58
59 #Check them
60 echo [OK] Start Main check cycle, whill check every $check_every seconds...
61 while true ; do
62 if ! timeout -k 1 $timeout_after ls "$bind_mountpoint" &>/dev/null ; then
63 echo no answer from bindfs for "$bind_mountpoint"
64 clean
65 break
66 #else
67 #echo Share is alive
68 fi
69 sleep $check_every
70 done
71
72 else
73 echo [!!] Cannot mount "$share" on "$cifs_mountpoint"
74 fi
75
76 echo [..] Waiting $restart_after seconds: $(date)
77 sleep $restart_after
78
79done