#!/bin/sh
#simple samba settings
#01micko 111122, 120215
#gpl3
#150925 BK change "gtkdialog4" to "gtkdialog".
#151002 BK change /root to /file. filter out comments from smb.conf
#170203 BK for easy linux, change /file to <path>/home. 170930 see samba template FIXUPHACK
#171214 BK entry box for samba password.
#171216 BK precaution, make sure smbpasswd has run. internationalized.
#171228 BK changed hostname text.
#180105 BK various refinements.
#180111 BK images now at /usr/share/pixmaps/easyshare
#180114 BK fix smb.conf, renamed samba.sh to samba-setup
#180125 BK improve samba security, restrict to local network. 180130 revert.
#180129 BK fix ip-address.

export TEXTDOMAIN=sambasetup
export OUTPUT_CHARSET=UTF-8

. /etc/rc.d/PUPSTATE #170203

#check for 1 running instance
RUNNING=`ps |grep SMBGUI|grep -v grep`
[ "$RUNNING" != "" ] && exit 0

# sort out the message app
type gxmessage 2>&1 >/dev/null && MSGAPP=gxmessage border='-borderless' || MSGAPP=xmessage border=
export MSGAPP border

#171214 save local sharename, username, password...
mkdir -p /var/local/easyshare
touch /var/local/easyshare/samba-shares-auth
LOCALHOSTNAME="$(grep ' localhost ' /etc/hosts | tr -s ' ' | cut -f 3 -d ' ' | tr '[a-z]' '[A-Z]')" #ex: PUPPYPC20940
[ "$(grep "^${LOCALHOSTNAME} " /var/local/easyshare/samba-shares-auth)" == "" ] && echo "${LOCALHOSTNAME} root woofwoof" >> /var/local/easyshare/samba-shares-auth
SAMBA_LOCAL_USER="$(grep "^${LOCALHOSTNAME} " /var/local/easyshare/samba-shares-auth | cut -f 2 -d ' ')"
#this is replaced with "XXXX..." if not "woofwoof"...
SAMBA_LOCAL_PASSWORD="$(grep "^${LOCALHOSTNAME} " /var/local/easyshare/samba-shares-auth | cut -f 3 -d ' ')"

LOCALIPADDRESS="$(hostname -I 2>/dev/null | cut -f 1 -d ' ')" #180125 180129
if [ ! "$LOCALIPADDRESS" ];then
 M_e1="$(gettext 'Samba Setup: error')"
 M_e2="$(gettext 'The IP address assigned to this computer could not be found. This probably means you do not have a network (and Internet) connection. Aborting.')"
 pupmessage -bg '#FFA0A0' -title "${M_e1}" "${M_e2}"
 exit
fi

##just in case
#171214 chmod 755 /etc/init.d/rc.samba

#is this config generated by this script? 180105 180125 do not ask.
grep -q 'EasyShare Samba Configuration' /etc/samba/smb.conf
if [ $? -ne 0 ];then
	#M_ss1="$(gettext 'Samba Setup')"
	#M_ss2="$(gettext 'Continue')"
	#M_ss3="$(gettext 'Quit')"
	#M_ss4="$(gettext 'You have a custom /etc/samba/smb.conf Samba configuration file.')"
	#M_ss5="$(gettext 'Samba Setup will create its own smb.conf, so if you continue, a backup will be made of the original, named smb.conf.old')"
	#Xdialog --wrap --title "${M_ss1}"  --ok-label "${M_ss2}" --cancel-label "${M_ss3}" --yesno "${M_ss4}\n\n${M_ss5}" 0 50
	#[ $? -ne 0 ]&& exit
	cp -af /etc/samba/smb.conf /etc/samba/smb.conf.old
fi

##check for custom smb.conf hmmmm multiple shares would conflict with this... would be better to work with ANY samba config..ie use sed or take the wbar approach. Rejects if longer than 3 entries.
#CUSTOM=`grep '^\[' /etc/samba/smb.conf|wc -l`
#if [ "$CUSTOM" -gt "3" ];then
#	Xdialog --title "Simple Samba Management" --ok-label="Continue" --cancel-label="Quit" --yesno "You have a custom Samba #configuration. \nThis tool will overwrite your /etc/samba/smb.conf \nhowever a backup will be made automatically. \nIt is #recommended you quit and \nconfigure Samba manually" 0 0 0
#	[ $? -ne 0 ]&& exit
#	cp -af /etc/samba/smb.conf /etc/samba/smb.conf.old
#fi

#detect if samba is running
status_func(){
	SAMBARUNNING=`pidof smbd|head -c1`
	if [ "$SAMBARUNNING" != "" ];then
		ln -sf /usr/share/pixmaps/easyshare/on.png /tmp/samba.png
	else
		ln -sf /usr/share/pixmaps/easyshare/off.png /tmp/samba.png
	fi
}

#switch samba daemon on/off
togglesamba_func(){
	SAMBARUNNING=`pidof smbd|head -c1`	
	if [ "$SAMBARUNNING" != "" ];then
		/etc/init.d/rc.samba stop
		chmod 644 /etc/init.d/rc.samba #171214 so won't run at bootup.
	else
		chmod 755 /etc/init.d/rc.samba #171214
		/etc/init.d/rc.samba start
		#171216 make sure default password is set first time enable daemon...
		SAMBA_LOCAL_USER="$(grep "^${LOCALHOSTNAME} " /var/local/easyshare/samba-shares-auth | cut -f 2 -d ' ')"
		SAMBA_LOCAL_PASSWORD="$(grep "^${LOCALHOSTNAME} " /var/local/easyshare/samba-shares-auth | cut -f 3 -d ' ')"
		[ "$SAMBA_LOCAL_PASSWORD" == "woofwoof" ] && echo -e "${SAMBA_LOCAL_PASSWORD}\n${SAMBA_LOCAL_PASSWORD}" | smbpasswd -a $SAMBA_LOCAL_USER
	fi
	sleep 1
	status_func
}

#generate smb.conf. 180125 improve security (see 'interfaces'). 
#180130 revert 'interfaces', removed: 
#	interfaces = ${LOCALIPADDRESS}/24 127.0.0.1
#	bind interfaces only = yes
swapvalues_func(){
 NETBIOSNAME="netbios name = $SERVERNAME"
 if [ "$SERVERNAME" = "" ];then
  NETBIOSNAME=""
 fi

 #180129 earlier LOCALIPADDRESS not visible here, do again...
 LOCALIPADDRESS="$(hostname -I 2>/dev/null | cut -f 1 -d ' ')"

	echo "#this is a very simple smb.conf to get you started
#coutesy rcrsn51 and gcmartin
[global]
	workgroup = $WGROUP
	$NETBIOSNAME
	server string = EasyShare Samba Configuration
	security = user
	map to guest = Bad Password
	printing = cups
	printcap name = cups
	load printers = yes
	unix extensions = yes

[$SHARENAME]
	path = $MYPATH
	writable = yes
" > /tmp/smb.conf

[ $MYPATH2 ]&& echo "
[$SHARENAME2]
	path = $MYPATH2
	writable = yes
" >> /tmp/smb.conf

[ $MYPATH3 ]&& echo "
[$SHARENAME3]
	path = $MYPATH3
	writable = yes
" >> /tmp/smb.conf

echo "
[printers]
	comment = All Printers
	path = /var/spool/samba
	browseable = no
	guest ok = yes
	writable = no
	printable = yes
" >> /tmp/smb.conf
#	[ "`grep BLANK /tmp/smb.conf`" != "" ]&& sed -i 's%BLANK%%' /tmp/smb.conf

}

#config test
testconfig_func(){
	testparm -s /tmp/smb.conf >/tmp/testparm.log 2>&1

	[ $? -ne 0 ]&& "$MSGAPP" -center -bg "#e77" -timeout 5 "ERROR: your smb.conf is not correct, try again" && return

	echo ""  >> /tmp/testparm.log
	SVPATH="`grep "path" /tmp/smb.conf| grep -v '^#'|awk '{print $3}'|head -n1`" #151002
	[ ! $SVPATH ] && echo "ERROR: SHARED PATH IS MISSING" >> /tmp/testparm.log || echo "Ok" >> /tmp/testparm.log
	WORKGROUPSET="`grep "workgroup" /tmp/smb.conf| grep -v '^#'|awk '{print $3}'`" #151002
	[ ! $WORKGROUPSET ] && echo "ERROR: WORKGROUP IS MISSING" >> /tmp/testparm.log || echo "Ok" >> /tmp/testparm.log
	"$MSGAPP" -file /tmp/testparm.log
}

#apply new settings if passes similar test to above... gui may have been altered after test to fresh config created anyway.
apply_func(){
	[ ! -x /etc/init.d/rc.samba ] && "$MSGAPP" -center -bg "#e77" -timeout 5 $border -buttons "" "ERROR: The Samba daemon is not running" && return #171214
	[ ! $MYPATH ] && "$MSGAPP" -center -bg "#e77" -timeout 5 $border -buttons "" "ERROR: Aborting, you must enter a share path" && return
	[ ! $WGROUP ] && "$MSGAPP" -center -bg "#e77" -timeout 5 $border -buttons "" "ERROR: Aborting, you must enter a workgroup" && return
	
	testparm -s /tmp/smb.conf >/tmp/testparm.log 2>&1
	[ $? -ne 0 ]&& "$MSGAPP" -center -bg "#e77" -timeout 20  "ERROR: Aborting, Something went wrong with the Samba configuration.
	 Check the log at /tmp/testparm.log. 
	 Please try again or consult the documentation in /usr/share/help
	 Your SAMBA config has NOT been changed" && return

	#171214
	if [ "$LOCALPASSWORD1" != "$LOCALPASSWORD2" ];then
	 pupmessage -bg '#FFA0A0' -title "Samba Setup Error" "Passwords are not the same"
	 return
	fi
	if [ "$(echo -n "$LOCALPASSWORD1" | tr -d '[a-zA-Z0-9]')" != "" ];then
	 pupmessage -bg '#FFA0A0' -title "Samba Setup Error" "Password may only contain a-z, A-Z and 0-9"
	 return
	fi
	PWflg=0
	[ "$LOCALPASSWORD1" == "woofwoof" ] && PWflg=1
	[ "$(echo -n "$LOCALPASSWORD1" | tr -d 'X')" != "" ] && PWflg=2
	
	cp -af /tmp/smb.conf /etc/samba/ #instate new smb.conf IF passes test
	chmod 755 /etc/init.d/rc.samba #171214
	/etc/init.d/rc.samba restart #171214 not as separate process
	pupmessage -bg '#A0FFA0' -timeout 6 -title "Samba daemon restarted" "The samba daeon has been restarted. You can check the log at /tmp/testparm.log"
	 
	if [ $PWflg -ne 0 ];then
	 echo -e "${LOCALPASSWORD1}\n${LOCALPASSWORD1}" | smbpasswd -a $SAMBA_LOCAL_USER
	 #anything other than "woofwoof" gets recorded as X's...
	 xSERVERNAME="$(echo -n "$SERVERNAME" | tr '[a-z]' '[A-Z]')"
	 sed -i "/${xSERVERNAME} /d" /var/local/easyshare/samba-shares-auth
	 [ $PWflg -eq 1 ] && PW='woofwoof'
	 [ $PWflg -eq 2 ] && PW="$(echo -n "$LOCALPASSWORD1" | tr '[a-zA-Z0-9]' 'X')"
	 echo "${xSERVERNAME} root ${PW}" >> /var/local/easyshare/samba-shares-auth
	fi
}

fix_smb_conf_func() { #180114
 #first time run Samba Setup, if just turn on daemon then hit quit button,
 #need to make sure have a valid smb.conf...
 pidof smbd >/dev/null
 [ $? -ne 0 ] && return 0
 grep -q 'EasyShare Samba Configuration' /etc/samba/smb.conf
 [ $? -eq 0 ] && return 0
 swapvalues_func
 apply_func
 status_func
}

export -f swapvalues_func
export -f testconfig_func
export -f status_func
export -f togglesamba_func
export -f apply_func
export -f fix_smb_conf_func

#just in case..I suspect not needed as would write a fresh one...should clean up at the end really
[ -f /tmp/smb.conf ] &&  rm -f /tmp/smb.conf

#initialise status button
status_func

#extract parameters or use fallbacks
MYPATH="`grep -iE 'path' /etc/samba/smb.conf| grep -v '^#' |grep -v 'var'|grep -v 'tmp'|awk 'NR==1{print $3}'`" #151002 fix
if [ ! "$MYPATH" ];then
 if [ "$WKG_DEV" ];then #170203
  MYPATH="/mnt/${WKG_DEV}/${WKG_DIR}home" #easy linux
 else
  MYPATH=/file #151002
 fi
fi

SHARENAME="`grep -iE '^\[' /etc/samba/smb.conf|grep -v 'global'|grep -v 'printers'|sed -e 's%\[%%' -e 's%\]%%'| awk 'NR==1'`"
[ ! $SHARENAME ]&& SHARENAME="puppyshare"

MYPATH2="`grep -iE 'path' /etc/samba/smb.conf| grep -v '^#'|grep -v 'var'|grep -v 'tmp'|awk 'NR==2{print $3}'`" #151002 fix
SHARENAME2="`grep -iE '^\[' /etc/samba/smb.conf|grep -v 'global'|grep -v 'printers'|sed -e 's%\[%%' -e 's%\]%%'| awk 'NR==2'`"
[ $MYPATH2 ]&& PATH2="<default>$MYPATH2</default>" && SHARE2="<default>$SHARENAME2</default>"

MYPATH3="`grep -iE 'path' /etc/samba/smb.conf| grep -v '^#'|grep -v 'var'|grep -v 'tmp'|awk 'NR==3{print $3}'`" #151002 fix
SHARENAME3="`grep -iE '^\[' /etc/samba/smb.conf|grep -v 'global'|grep -v 'printers'|sed -e 's%\[%%' -e 's%\]%%' | awk 'NR==3'`"
[ $MYPATH3 ]&& PATH3="<default>$MYPATH3</default>" && SHARE3="<default>$SHARENAME3</default>"

CURSERVER="`grep "netbios" /etc/samba/smb.conf| grep -v '^#'|awk '{print $4}'`" #151002 fix
[ ! $CURSERVER ] && CURSERVER="$(hostname)"

WGROUP="`grep "workgroup" /etc/samba/smb.conf| grep -v '^#'|awk '{print $3}'`" #151002 fix

if [ "$SAMBA_LOCAL_PASSWORD" == "woofwoof" ];then
 M_s1="$(gettext 'It is recommended that the password be changed.') "
 M_p0="$(gettext 'It must be something that you can remember.')"
 M_p1=" $(gettext 'The default password is <b>woofwoof</b>. It is recommended that this be changed')"
else
 M_s1=""
 M_p0="$(gettext "It is displayed here as X's for security reasons.")"
 M_p1=" $(gettext 'Only type a new password in here if you want to change it')"
fi

#180105
#   <button tooltip-text=\"$(gettext 'Click to check your new settings without applying')\">
#    <label>Test</label>
#	<input file stock=\"gtk-index\"></input>
#    <action>swapvalues_func</action>
#	<action>testconfig_func</action>
#   </button>

#GUI
export SMBGUI="<window title=\"$(gettext 'Samba Setup')\" icon-name=\"gtk-network\" resizable=\"false\">
 <vbox>
  <hbox homogeneous=\"true\">
   <text use-markup=\"true\"><label>\"<b>$(gettext 'Configure Samba here!')</b>\"</label></text>
  </hbox> 
  <hbox homogeneous=\"true\">
   <text use-markup=\"true\"><label>\"$(gettext 'The Samba daemon must be running to use Samba.') ${M_s1}$(gettext 'Leave the other settings alone, unless you really need to change them')\"</label></text>
  </hbox>
  <hseparator></hseparator>
  
  <hbox>
   <pixmap>
    <height>40</height>
    <input file>/usr/share/pixmaps/easyshare/samba.png</input>
   </pixmap>
   <text><label>$(gettext 'Switch Samba Daemon on or off:')</label></text>
   <button tooltip-text=\"$(gettext 'Clicking this button when Green will turn off Samba, clicking when Red will turn on Samba')\">
     <variable>ARTWORK</variable>
	 <input file>/tmp/samba.png</input>
	 <action>togglesamba_func</action>
     <action type=\"refresh\">ARTWORK</action>
    </button>
  </hbox>
  <hseparator></hseparator>
  
  <hbox homogeneous=\"true\">
   <text use-markup=\"true\"><label>\"$(gettext 'The <b>hostname</b> is the name of this computer, to identify it on the network.')\"</label></text> 
  </hbox> 
  <hbox homogeneous=\"true\">
   <text><label>\"         \"</label></text>
   <text use-markup=\"true\"><label>\"Hostname:\"</label></text>
   <entry tooltip-text=\"$(gettext 'You can change the hostname of your computer to anything you like as long as there are no spaces and characters are alpha/numeric. Dots, dashes and underscores are allowed')\">
    <default>$CURSERVER</default>
    <variable>SERVERNAME</variable>
   </entry>
  </hbox>
  <hseparator></hseparator>

  <hbox homogeneous=\"true\">
   <text use-markup=\"true\"><label>\"$(gettext 'This is the password for local shares to be made available to other computers.') ${M_p0}${M_p1}\"</label></text> 
  </hbox>
  <hbox>
   <entry visibility=\"true\" tooltip-text=\"$(gettext 'Type a password that you can remember')\">
    <default>${SAMBA_LOCAL_PASSWORD}</default>
    <variable>LOCALPASSWORD1</variable>
   </entry>
   <text><label> $(gettext 'Verify:')</label></text>
   <entry visibility=\"true\" tooltip-text=\"$(gettext 'Retype the password here')\">
    <default>${SAMBA_LOCAL_PASSWORD}</default>
    <variable>LOCALPASSWORD2</variable>
   </entry>
  </hbox>

  <hseparator></hseparator>
  
  <hbox homogeneous=\"true\">
   <text use-markup=\"true\"><label>\"$(gettext 'This is the share name and path.') $(gettext 'Change either or both if you wish. You can have up to three shares.')\"</label></text>
  </hbox>
  
  <hbox>
   <entry tooltip-text=\"$(gettext 'This is a share name for the Samba server. You can change it to anything you like as long as there are no spaces and characters are alpha/numeric. Dots, dashes and underscores are allowed')\">
    <variable>SHARENAME</variable>
    <default>$SHARENAME</default>
   </entry>
   <entry fs-action=\"folder\" tooltip-text=\"$(gettext 'This is the folder that will be available for other computers to access')\">
    <variable>MYPATH</variable>
    <default>$MYPATH</default>
   </entry>
   <button tooltip-text=\"$(gettext 'Browse for suitable share path')\">
	<input file stock=\"gtk-open\"></input>
	<action>fileselect:MYPATH</action>
   </button>
  </hbox>
  
    <hbox>
   <entry tooltip-text=\"$(gettext 'Add a second share here')\">
    <variable>SHARENAME2</variable>
	$SHARE2
   </entry>
   <entry fs-action=\"folder\">
    <variable>MYPATH2</variable>
   $PATH2
   </entry>
   <button tooltip-text=\"$(gettext 'Browse for suitable share path')\">
	<input file stock=\"gtk-open\"></input>
	<action>fileselect:MYPATH2</action>
   </button>
  </hbox>
  
     <hbox>
   <entry tooltip-text=\"$(gettext 'Add a third share here')\">
    <variable>SHARENAME3</variable>
    $SHARE3
   </entry>
   <entry fs-action=\"folder\">
    <variable>MYPATH3</variable>
  $PATH3
   </entry>
   <button tooltip-text=\"$(gettext 'Browse for suitable share path')\">
	<input file stock=\"gtk-open\"></input>
	<action>fileselect:MYPATH3</action>
   </button>
  </hbox>
  
  <hseparator></hseparator>
  
  <hbox homogeneous=\"true\">
   <text><label>\"         \"</label></text>
   <text use-markup=\"true\"><label>\"$(gettext '<b>Workgroup</b> name:')\"</label></text> 
   <entry tooltip-text=\"$(gettext 'If you have Microsoft Windows machines on your network you should set the Workgroup to the same name as the Windows Workgroup, which is usually WORKGROUP')\">
    <default>$WGROUP</default>
    <variable>WGROUP</variable>
    </entry>
  </hbox>
  <hseparator></hseparator>

  <hbox homogeneous=\"true\">
   <button image-position=\"1\" use-stock=\"true\" label=\"gtk-apply\" tooltip-text=\"$(gettext 'Apply any changes made above, then restart the Samba daemon')\">
   <action>swapvalues_func</action>
    <action>apply_func</action>
    <action>status_func</action>
    <action type=\"refresh\">ARTWORK</action>
   </button>
   <button image-position=\"1\" use-stock=\"true\" label=\"gtk-quit\" tooltip-text= \"$(gettext 'Exit leaving your current settings and status alone')\">
    <action>fix_smb_conf_func</action>
    <action>exit:quit</action>
   </button>
  </hbox>
 </vbox>
</window>"

gtkdialog -c --program=SMBGUI

