#!/bin/sh
#(c) Copyright Nov 2007 Barry Kauler www.puppylinux.com
#2007 Lesser GPL licence v2 (http://www.fsf.org/licensing/licenses/lgpl.html)
#a complete rewrite for Puppy 'Dingo', Nov 27 2007, Dec 1,5 2007.
#v3.95 4jan2007: -x option for rox.
#v3.96 17jan2008: full install, mounted '/' partition was not shown.
#v3.98 13mar2008: switch probepart and mut2 engines.
#v3.99 7apr2008: fix zombie process prevents partition unmount.
#v4.01 7may2008: allow /sbin/pup_ueventd to kill pmount and cause it to restart.
#v4.01 10may2008: using 'probedisk2' script.
#v4.01 10may2008: redesign of xml generation, much more efficient.
#v4.01 11may2008: passed params sd,sr,mm,fd when called from pup_dock_xx tray applets.
#v4.01 13may2008: introduce 'preferences' button, add toggle tabbed-normal view.
#v4.01 17may2008: make sure top tab stays on top when mount/unmount.
#v4.01 18may2008: auto launch of pmount when a drive plugged is now confgurable, see prefs.
#v4.02 31may2008: refresh desktop icons when mount/unmount (see pup_eventd).
#v404 11jul08: unipup, disable unmount button correctly.
#v407 mut bugfix.
#v408 bugfix, a drive with no valid partitions crashed pmount.
#v409 jesse: bugfix for floppy detection when using mut2 engine.
#v410 catch case no valid partitions/drvs in a category, remove that category.
#v411 added 'quiet' option for vfat, suppresses error msg when file attribs not preserved on copy.
#v412, no, do not exit if only a warning error msg.
#v420JPa1 4Jun09: fix mount iso9660, ext2/ext3
# 27jun09 I18N, vfat mount options by Masaki Shinomiya <shino@pos.to>
# 08jul09 ask to eject CD
#w476 fix codepage for vfat f.s. ... neglected by Masaki Shinomiya
#w477 fix pmount crash when running xvesa.
#100127 codepage fixes. 100131 iso9660 fix.
#101005 maddox: added m_40 cancel message, fixed usage of m_31.
#110208 zigbert: improve gui layout. bk: put this on-hold for now, see 3 commented lines.
#110505 support sudo for non-root user.
#110720 should not open a layer inside aufs, ex: session saved entire partition, desktop drive icon is /initrd/pup_rw.
#110814 01micko: convert script from gtkdialog2 to gtkdialog3+.
#120203 preferences was broken.
#120129 karl godt: fix ZOMBIES, see http://murga-linux.com/puppy/viewtopic.php?t=71767&start=420. see also rc.shutdown, drive_all, pup_event_frontend_d.
#120323 partial replace 'gxmessage' with 'pupmessage'.
#120411 zigbert: gui rewrite, volume-lables, integration of partview, mount at boot
#130128 convert "technosaurus method" i18n to gettext. mut2 option removed (very old, no longer works properly).
#130128 fixed for 'udf' f.s. (see also pup_event_frontend_d, drive_all, probepart).
#130205 zigbert: correct size of bar to report used space on filesystem.
#130216 support f2fs.
 
[ "`whoami`" != "root" ] && exec sudo -A ${0} ${@} #110505

#NOTE: not to clash with 'pmount.mo' used by previous i18n method.
export TEXTDOMAIN=pupmount
export OUTPUT_CHARSET=UTF-8
. gettext.sh

#using ${$} which is pid of script...
MYPID=${$}

. /etc/rc.d/PUPSTATE #v3.96
export PMOUNT="pmount" #name of this executable.
. /etc/rc.d/functions4puppy4 #v4.02

#build script to reload gui from mountme funtion
echo 'TMP="`ps`"; for I in `echo "$TMP" | grep -F "pmount" | awk '"'"'{print $1}'"'"'`; do kill -9 $I 2> /dev/null; done; exec /usr/sbin/'"$PMOUNT $TOPACTUAL" > /tmp/pmount_reload
chmod 722 /tmp/pmount_reload
#---

#read config - this does not include options from the preferences window
[ -f $HOME/.pmountrc ] && . $HOME/.pmountrc
if [ ! "$HEIGHT" ]; then
	HEIGHT=350 
	WIDTH=500
	export COLOR_SPACEFREE='#3FA04E'
	export COLOR_SPACEUSED='#D7302A'
	export COLOR_SPACELOCKED='#EDBF4D'
fi

###################################################################################
#                                                                                 #
#                              F U N C T I O N S                                  #
#                                                                                 #
###################################################################################


buildheading (){
	ONEDISK="$1"
	ONECATEGORY="$2"
	ONEDISKDESCR="$3"
	ONEDISKNAME="`echo "$ONEDISK" | cut -f 3 -d '/'`"
	
 	case $ONECATEGORY in
		drive) 
			ICON=/usr/local/lib/X11/pixmaps/drive48.png
			PARTSIZE="`parted $ONEDISK print | grep "^Disk" | cut -d: -f2 | tr -d ' '`"
			;;
		optical)
			ICON=/usr/local/lib/X11/pixmaps/optical48.png
			PARTSIZE=''
			;;
		usbdrv)
			ICON=/usr/local/lib/X11/pixmaps/usbdrv48.png
			PARTSIZE="`parted $ONEDISK print | grep "^Disk" | cut -d: -f2 | tr -d ' '`"
			;;
		card)
			ICON=/usr/local/lib/X11/pixmaps/card48.png
			PARTSIZE="`parted $ONEDISK print | grep "^Disk" | cut -d: -f2 | tr -d ' '`"
			;;
		floppy)
			ICON=/usr/local/lib/X11/pixmaps/floppy48.png
			PARTSIZE=''
			;;
	esac
	if [ "`echo $ONECATEGORY | grep -E "optical|usbdrv|card"`" ] && [ "`mount | grep "^$ONEDISK"`" ]; then
		PIXLOCK='<circle cx="18" cy="18" r="14" style="fill:#F1AB24;stroke:#875900;stroke-width:2;fill-opacity:0.8;stroke-opacity:0.6"/>
  <path fill="#333333" d="m 19,8 c -4,0 -6,2 -6,4 0,1 0,3 0,3 0,0 -1,0 -2,0 0,2 0,5 0,8 0,2 2,3 4,3 3,0 5,0 8,0 1,0 3,-1 3,-3 0,-3 0,-5 0,-8 -1,0 -2,0 -2,0 l 0,-3 C 24,9 21,8 19,8 z m 3,5 0,2 -7,0 c 0,-3 0,-2 0,-2 0,-2 1,-3 4,-3 1,0 3,1 3,3 z m -3,4 c 1,0 2,2 0,3 l 1,4 -3,0 1,-4 c -2,-1 -1,-3 1,-3 z"/>'
	else
		PIXLOCK=''
	fi
	echo '
	<svg version="1.0" width="350" height="60" id="svg1"
	  xmlns:xlink="http://www.w3.org/1999/xlink">

	  <defs
		 id="defs4">
		<linearGradient id="LGD_01">
		  <stop style="stop-color:#111;stop-opacity:1" offset="0" />
		  <stop style="stop-color:#111;stop-opacity:0" offset="1" />
		</linearGradient>
		<linearGradient id="LG_01"
		   x1="-10" y1="-40" x2="20" y2="80"	  
		   xlink:href="#LGD_01"
		   gradientUnits="userSpaceOnUse" />
	  </defs>

	  <rect
		 style="fill:url(#LG_01);fill-opacity:1;fill-rule:evenodd;stroke-width:0;stroke:#404040;stroke-opacity:1;stroke-dasharray:none;"
		 width="350" height="60"/>
	  <image xlink:href="'${ICON}'" width="48" height="48" x="5" y="5"/>
	  '"$PIXLOCK"'
	  <text
		 style="fill:#111;stroke:none;font-family:DejaVu;font-style:normal;font-weight:medium;font-size:16;fill-opacity:1;stroke-opacity:1;stroke-width:3pt;stroke-linejoin:miter;stroke-linecap:butt;text-anchor:start;writing-mode:lr;"
		 x="75" y="20">
		 '${ONEDISKDESCR}'
	  </text>
	  <text
		 style="fill:#111;stroke:none;font-family:DejaVu;font-style:normal;font-weight:medium;font-size:12;fill-opacity:1;stroke-opacity:1;stroke-width:3pt;stroke-linejoin:miter;stroke-linecap:butt;text-anchor:start;writing-mode:lr;"
		 x="75" y="40">
		 '$PARTSIZE'
	  </text>
	</svg>' > /tmp/pmount_${ONEDISKNAME}_svg
}

buildpix (){
	ONEPART="$1"
	ONEDEV="$2"
	ONECATEGORY="$3"

	DEVPATTERN="^${ONEDEV} "
	ONEMNTPT="`mount | grep "$DEVPATTERN" | cut -f 3 -d ' '`"
	DEVNAME="`echo -n "$ONEDEV" | cut -f 3 -d '/'`"

	#size
	if [ "$ONEFS" != "cdda" ]; then
		export ONESIZEK=`echo -n "$ONEPART" | cut -f 3 -d '|'`
		[ "$ONESIZEK" = 0 ] && ONESIZEK=1 #calculation of percent (svg) fails if size is 0 (ie. a blank CD)
		if [ $ONESIZEK -gt 1073741824 ];then #1024*1024*1024
			ONESIZE="`dc $ONESIZEK 1073741824 \/ p`"
			ONESIZE="`printf "%.1f" $ONESIZE`T"
		elif [ $ONESIZEK -gt 1048576 ];then #1024*1024
			ONESIZE="`dc $ONESIZEK 1048576 \/ p`"
			ONESIZE="`printf "%.1f" $ONESIZE`G"
		else
			if [ $ONESIZEK -gt 99 ];then
				ONESIZE="`expr $ONESIZEK \/ 1024`M"
			else
				ONESIZE="`dc $ONESIZEK 1024 \/ p`"
				ONESIZE="`printf "%.1f" $ONESIZE`M"
			fi
		fi
		if [ "$ONESIZE" = "0.0M" ] || [ "$ONESIZE" = "0M" ]; then ONESIZE=""; fi
	fi

	#free space
	if [ ! "$ONEMNTPT" ]; then
		FREEK=$ONESIZEK
		export PIXTEXT="${ONESIZE}"
	else 
		export FREEK=`df -k | tr -s ' ' | grep -m1 "$DEVPATTERN" | cut -f 4 -d ' '`
		[ ! "$FREEK" ] && FREEK=$ONESIZEK
		if [ $FREEK -gt 1073741824 ];then #1024*1024*1024
			ONEFREE="`dc $FREEK 1073741824 \/ p`"
			ONEFREE="`printf "%.1f" $ONEFREE`T"
		elif [ $FREEK -gt 1048576 ];then #1024*1024
			ONEFREE="`dc $FREEK 1048576 \/ p`"
			ONEFREE="`printf "%.1f" $ONEFREE`G"
		else
			if [ $FREEK -gt 99 ];then
				ONEFREE="`expr $FREEK \/ 1024`M"
			else
				ONEFREE="`dc $FREEK 1024 \/ p`"
				ONEFREE="`printf "%.1f" $ONEFREE`M"
			fi
		fi
		if [ "$ONEFREE" = "0.0M" ] || [ "$ONEFREE" = "0M" ]; then ONEFREE=""; fi
		export PIXTEXT="${ONESIZE} / ${ONEFREE}"
	fi
	
	if [ "$ONECATEGORY" != "optical" ]; then
		 /usr/lib/gtkdialog/svg_bar 120 "$((($ONESIZEK-$FREEK)*120/$ONESIZEK))" "$PIXTEXT"  > /tmp/pmount${DEVNAME}_svg
	else
		 /usr/lib/gtkdialog/svg_bar 120 0 "$(gettext 'N/A')"  > /tmp/pmount${DEVNAME}_svg
	fi
}

volumelabel (){
	DODEV="$1"
	DEVNAME="`echo -n "$DODEV" | cut -f 3 -d '/'`"
	export inputbox='
	<window title="pMount - '$(gettext 'Puppy Drive Mounter')'">
	<vbox>
	  <frame '$(gettext 'Edit label')' - '$DODEV'>
	    <entry activates-default="true">
		  <variable>VOLUME_LABEL</variable>
		  <input>cat /tmp/pmount_'${DEVNAME}'_LABEL</input>
	    </entry>
	  </frame>
	  <hbox>
	    <button>
	      '"`/usr/lib/gtkdialog/xml_button-icon cancel`"'
	      <label>'$(gettext 'Cancel')'</label>
	      <action type="exit">cancel</action>
	    </button>
	    <button can-default="true" has-default="true" use-stock="true">
          '"`/usr/lib/gtkdialog/xml_button-icon ok`"'
	      <label>'$(gettext 'Ok')'</label>
	      <action type="exit">OK</action>
	    </button>
	  </hbox>
	</vbox>
	</window>'
	I=$IFS; IFS=""
	for STATEMENTS in  $(gtkdialog -p inputbox --center); do
		eval $STATEMENTS
	done
	IFS=$I
	if [ $EXIT = OK ]; then
		e2label $DODEV "$VOLUME_LABEL"
		echo "$VOLUME_LABEL" > /tmp/pmount_${DEVNAME}_LABEL
	fi
}

mountme (){
	DODEV="`echo -n "$1" | cut -f 2 -d '_'`"
	DEVNAME="`echo -n "$DODEV" | cut -f 3 -d '/'`"
	DOFS="`echo -n "$1" | cut -f 3 -d '_'`"
	devPATTERN='^'"$DEVNAME"'|'
	TOPACTUAL="`echo "$DEV2TAB" | tr ' ' '\n' | grep "$devPATTERN" | cut -f 2 -d '|'`" #find top tab.
	if [ "`echo "$1" | grep -F 'DOMOUNT'`" ];then
		mkdir -p /mnt/$DEVNAME
		case $DOFS in
			ntfs)
				#'mount' is a script that takes care of mounting ntfs... 100127...
				mount -t ntfs $DODEV /mnt/$DEVNAME
				RETVAL1=$?
				;;
			vfat)
				NLS_PARAM=""
				if [ -f /etc/codepage ]; then #100127...
					grep -q '850' /etc/codepage && [ "$(echo $LANG|cut -d'.' -f1)" != "en_US" ] && NLS_PARAM=",codepage=850"
					grep -q '852' /etc/codepage && NLS_PARAM=",codepage=852,iocharset=iso8859-2"
				fi
				echo $LANG | grep -q -i '\.utf' && NLS_PARAM="$NLS_PARAM,utf8"
				mount -t vfat -o shortname=mixed,quiet$NLS_PARAM $DODEV /mnt/$DEVNAME #v411 added quiet.
				RETVAL1=$?
				;;
			#100127 not certain about this (inserted by shinobar)... 100131 shinobar informs needed for cds created in windows...
			iso9660|udf) #130128 add udf.
				mount -t $DOFS -o iocharset=utf8 $DODEV /mnt/$DEVNAME
				RETVAL1=$?
				;;  
			*)
				mount -t $DOFS $DODEV /mnt/$DEVNAME
				RETVAL1=$?
				;;
		esac
		if [ $RETVAL1 -eq 0 ]; then
			#v3.95 -x option to rescan...
			exec rox -x /mnt/$DEVNAME -d /mnt/$DEVNAME #want this window on top.
		else
			/usr/lib/gtkdialog/box_ok "pMount - $(gettext 'Puppy Drive Mounter')" error "$(gettext "Unable to mount") $DEVNAME"
			exec /tmp/pmount_reload
		fi
	else
		MNTPT="`echo -n "$1" | cut -f 4 -d '_'`"
		[ ! "$MNTPT" ] && MNTPT=/mnt/$DEVNAME

		rox -D $MNTPT
		sync
		umount $DODEV ; umVAL=$?
		#v3.99 fix zombie process prevents partition unmount, invisible to fuser...
		if [ $umVAL -ne 0 ];then
			#120129 karl godt: fix ZOMBIES, see http://murga-linux.com/puppy/viewtopic.php?t=71767&start=420 ...
			ZOMBIES="`ps -H -A | grep '<defunct>' | sed 's/^[[:blank:]]*//;s/  /|/g' | grep -v '|||' | cut -f 1 -d ' ' | tr '\n' ' '`"
			for ONEZOMBIE in $ZOMBIES; do
				echo "Killing parentless zombie process $ONEZOMBIE"
				kill $ONEZOMBIE
			done
			umount $DODEV ; umVAL=$?
		fi
		#v3.99 rare ocassion, partition got unmounted before umount runs above...
		umPATTERN="${MNTPT} "
		[ "`mount | grep "$umPATTERN"`" = "" ] && umVAL=0

		if [ $umVAL -ne 0 ];then
			EXTRAMSG0="`fuser -v -m $MNTPT`"  
			if [ "$EXTRAMSG0" = "" ];then
				/usr/lib/gtkdialog/box_ok "pMount - $(gettext 'Puppy Drive Mounter')" error "$(gettext 'FAILURE! In the case of removable media, the most common reason is the media is not currently inserted. If so, please remedy.')"
			else
				gxmessage -wrap -bg "#ff99ff" -title "pMount - $(gettext 'Puppy Drive Mounter')" -center -buttons "$(gettext 'KILL')":10,"$(gettext 'EXIT')":20 "$(gettext 'FAILURE!')
$(gettext 'One or more processes (programs) are currently
using the partition. Here they are:')
${EXTRAMSG0}
 
$(gettext "If you press the 'KILL' button, Puppy will attempt to
kill the offending programs for you. Only do this as a
last resort.")
$(gettext "Firstly you should try to close the programs
manually, so do not press 'KILL'.")
$(gettext "PLEASE PRESS THE 'EXIT' BUTTON!")"


				[ $? -eq 10 ] && fuser -k -m $MNTPT
			fi
			exec /tmp/pmount_reload
		else
			if [ "$DOFS" = "iso9660" ]; then
				eject $DODEV
				/usr/lib/gtkdialog/box_ok "pMount - $(gettext 'Puppy Drive Mounter')" info "$(gettext 'Remove media, then press <b>Ok</b>')"
				eject -t $DODEV
				exec /tmp/pmount_reload
			fi
		fi
	fi
}

writeconfig (){
	XWININFO=`xwininfo -stats -name pMount`
	HEIGHT=`echo "$XWININFO" | grep 'Height:' | awk '{print $2}'`
	WIDTH=`echo "$XWININFO" | grep 'Width:' | awk '{print $2}'`
	X1=`echo "$XWININFO" | grep 'Absolute upper-left X' | awk '{print $4}'`
	Y1=`echo "$XWININFO" | grep 'Absolute upper-left Y' | awk '{print $4}'`
	X2=`echo "$XWININFO" | grep 'Relative upper-left X' | awk '{print $4}'`
	Y2=`echo "$XWININFO" | grep 'Relative upper-left Y' | awk '{print $4}'`
	X=$(($X1-$X2))
	Y=$(($Y1-$Y2))
	#---
	
	
	echo "#pMount config"											 > $HOME/.pmountrc
	echo "export COLOR_SPACEFREE='#3FA04E'"							>> $HOME/.pmountrc
	echo "export COLOR_SPACEUSED='#D7302A'"							>> $HOME/.pmountrc
	echo "export COLOR_SPACELOCKED='#EDBF4D'"						>> $HOME/.pmountrc
	echo -e "\n#Geometry"											>> $HOME/.pmountrc
	echo "export HEIGHT=\"$HEIGHT\""								>> $HOME/.pmountrc
	echo "export WIDTH=\"$WIDTH\""									>> $HOME/.pmountrc
	echo "export X=\"$X\""											>> $HOME/.pmountrc
	echo "export Y=\"$Y\""											>> $HOME/.pmountrc
}

export -f buildheading buildpix volumelabel mountme writeconfig





###################################################################################
#                                                                                 #
#                                P R O G R A M                                    #
#                                                                                 #
###################################################################################


/usr/lib/gtkdialog/box_splash -close never -fontsize large -text "$(gettext 'Please wait, probing hardware...')" & #110720
X1PID=$!

#v4.01 passed param, choose which tab to be "on top"...
TOPTAB=''
if [ $1 ];then
 TOPTAB="$1" #also allow full tab names usbdrv,optical,drive,card,floppy to be passed.
 [ "$1" = "any" ] && TOPTAB="drive" #see pup_eventd
 #pup_eventd calls pmount with just two letters...
 [ "$1" = "sd" ] && TOPTAB="usbdrv"
 [ "$1" = "sr" ] && TOPTAB="optical"
 [ "$1" = "mm" ] && TOPTAB="card"
 [ "$1" = "fd" ] && TOPTAB="floppy"
fi

PROBEPART="probepart"
PROBEDISK="probedisk"

#v4.01 toggle tabbed interface...
SINGLEFLAG="true" #default tabbed interface.
[ -f /root/.pmountsingle ] && SINGLEFLAG="`cat /root/.pmountsingle`"

#v4.02 quit immediately after choosing to mount/umount a partition... v404 change to false
PMOUNTQUIT="false" #"true" v404 change to false
[ -f /root/.pmountquit ] && PMOUNTQUIT="`cat /root/.pmountquit`"
#but if starting pmount from menu or 'drives' icon, do not quit...
[ "$1" = "any" -o "$1" = "" ] && PMOUNTQUIT="false"

#v3.96 'mount' misreports which partition mounted on '/'...
ROOTDEV2=""
[ "$PUPMODE" = "2" ] && ROOTDEV2="`df | grep ' /$' | grep '^/dev/' | cut -f 1 -d ' '`"

DISKINFO="`$PROBEDISK | sort -k 2 --field-separator='|'`" #v4.01
PARTSINFO="`$PROBEPART -k | grep -v 'none' | tr ' ' '_' | tr '\t' '_' | cut -f 1-3 -d '|'`" #v3.98 fix for mut2.

#add floppy drive, if any (note, zip detected by probedisk/probepart)...
if [ -e /sys/block/fd0 ];then
 DISKINFO="/dev/fd0|floppy|floppy disk drive
$DISKINFO"
 PARTSINFO="/dev/fd0|vfat|1440
$PARTSINFO"
fi

#v4.01 reorganise so that a particular tab is on top...
if [ "$TOPTAB" != "" ];then
 toptabPATTERN='|'"$TOPTAB"'|'
 TOPDISKS="`echo "$DISKINFO" | grep "$toptabPATTERN"`"
 if [ "$TOPDISKS" != "" ];then
  DISKINFO="${TOPDISKS}
`echo "$DISKINFO" | grep -v "$toptabPATTERN"`"
 fi
fi

#v410 catch case no valid partitions/drvs in a category, remove that category...
echo -n "" > /tmp/pmount_cat_test1
for ONEDISK in `echo "$DISKINFO" | cut -f 1,2 -d '|' | tr '\n' ' '`
do
 ONEDRVNAME="`echo -n "$ONEDISK" | cut -f 1 -d '|'`"
 ONEDRVCAT="`echo -n "$ONEDISK" | cut -f 2 -d '|'`"
 if [ "`echo "$PARTSINFO" | grep "$ONEDRVNAME" | grep -v '|none|'`" != "" ];then
  echo "$ONEDRVCAT" >> /tmp/pmount_cat_test1
 fi
done
for ONECAT in `echo "$DISKINFO" | cut -f 2 -d '|' | sort -u | tr '\n' ' '`
do
 if [ "`grep "$ONECAT" /tmp/pmount_cat_test1`" = "" ];then
  diPATTERN="|${ONECAT}|"
  NEWDISKINFO="`echo "$DISKINFO" | grep -v "$diPATTERN"`"
  DISKINFO="$NEWDISKINFO"
 fi
done

#v4.01 find the tabs...
#old probedisk has: cdrom, disk, floppy, Direct-Access.
#probedisk2 has: drive, optical, usbdrv, card, floppy
TABLIST="`echo -n "$DISKINFO" | cut -f 2 -d '|' | uniq | tr '\n' '|' | sed -e 's/|$//'`"
CURRENTTAB=''

#v408 v410 moved up...  130216 added f2fs...
VALIDPARTS="`echo "$PARTSINFO" | grep -E 'btrfs|ext2|ext3|ext4|f2fs|hfs|iso9660|jfs|minix|msdos|ntfs|reiser|udf|vfat|xfs'`" #130128

#get actual top tab...
TOPACTUAL="`echo "$TABLIST" | cut -f 1 -d '|'`"

#v4.01 PARTSINFO has to be sorted in same order as the categories in DISKINFO...
PARTSGUI=""
FRAMEFLAG="off"
export DEV2TAB=""
OLDDISKNAME=''

for ONEDISK in `echo "$DISKINFO" | cut -f 1 -d '|' | tr '\n' ' '`
do

 #v408 bug fix, a drive with no valid partitions, skip it...
 [ "`echo "$VALIDPARTS" | grep "$ONEDISK"`" = "" ] && continue
 
 ONEDISKNAME="`echo "$ONEDISK" | cut -f 3 -d '/'`"
 DSKPATTERN="^${ONEDISK}|"
 ONEDISKDESCR="`echo "$DISKINFO" | grep "$DSKPATTERN" | cut -f 3 -d '|' | tr '\-' '@' | sed -e 's/[^a-zA-Z0-9 @_]//g' | tr '@' '-'`"
 xDSKPATTERN="^${ONEDISK}"
 cutPARTSINFO="`echo "$PARTSINFO" | grep "$xDSKPATTERN" | tr '\n' ' '`"
 [ "$cutPARTSINFO" = "" ] && continue #fix for superfloppy-drv with unknown f.s.
 [ "$cutPARTSINFO" = " " ] && continue #v408 er, there will be a single space.
 #group one or more frames in same tab...
 ONECATEGORY="`echo "$DISKINFO" | grep "$DSKPATTERN" | cut -f 2 -d '|'`" #drive,optical,usbdrv,card,floppy
 if [ "$CURRENTTAB" = "" ];then
  PARTSGUI="${PARTSGUI}<vbox scrollable=\"true\">"
  TABFLAG="on"
 else
  [ "$CURRENTTAB" != "$ONECATEGORY" ] && PARTSGUI="${PARTSGUI}</vbox><vbox scrollable=\"true\">"
 fi
 CURRENTTAB="$ONECATEGORY"
 

	buildheading ${ONEDISK} ${ONECATEGORY} "${ONEDISKDESCR}"
	PARTSGUI="${PARTSGUI}
	<vbox spacing=\"0\">
	 <hbox space-expand=\"false\" space-fill=\"false\">
	  <pixmap space-expand=\"false\" space-fill=\"false\"><variable>PIX_DISK_${ONEDISKNAME}</variable><input file>/tmp/pmount_${ONEDISKNAME}_svg</input></pixmap>
	  <hbox space-expand=\"true\" space-fill=\"true\"><text><label>\"\"</label></text></hbox>
	 </hbox>"


###############################################################################
for ONEPART in $cutPARTSINFO
do
 ONEDEV="`echo -n "$ONEPART" | cut -f 1 -d '|'`"
 DEVNAME="`echo -n "$ONEDEV" | cut -f 3 -d '/'`"
 export DEV2TAB="${DEV2TAB} ${DEVNAME}|${CURRENTTAB}" #remember which tab a partition is in.
 ONEFS="`echo -n "$ONEPART" | cut -f 2 -d '|'`"

 DEVPATTERN="${ONEDEV} "
 ONEMNTPT="`grep "$DEVPATTERN" /proc/self/mountinfo | grep '/ ' | cut -f 5 -d ' '`"
 [ "$ROOTDEV2" != "" ] && [ "$ROOTDEV2" = "$ONEDEV" ] && ONEMNTPT='/' #v3.96
 
 #in some cases prevent unmounting...
 INVISBUT=""
 if [ "`echo -n "$ONEMNTPT" | grep '^/initrd'`" -o "$ONEMNTPT" = "/" ]; then INVISBUT='<visible>disabled</visible>'; fi
 #v404 unipup, cannot unmount anything mntd in /.mnt...
 case $PUPMODE in
 16|24|17|25)
  [ "`echo -n "$ONEMNTPT" | grep '^/\.mnt'`" ] && INVISBUT='<visible>disabled</visible>'
  #usr_xxx.sfs was not copied to ram, still on partition...
  [ "`losetup | grep -o ' /.*/usr_.*\.sfs' | cut -f 1-3 -d '/' | cut -f 2 -d ' '`" = "$ONEMNTPT" ] && INVISBUT='<visible>disabled</visible>'
 ;;
 esac
 
   #if 'home' partition, substitute /mnt/home...
  if [ -L /mnt/home -a "`echo "$ONEMNTPT" | grep '/initrd/'`" != "" ];then
   HOMELINK="`readlink /mnt/home`"
   [ "$HOMELINK" = "$ONEMNTPT" ] && ONEMNTPT="/mnt/home"
  fi
  #110720 should not open a layer inside aufs, ex: session saved entire partition, desktop drive icon is /initrd/pup_rw...
  case $ONEMNTPT in
   /initrd/pup_*)
    ONEMNTPT="/" #open rox at top of aufs layers.
   ;;
  esac
  
 
 
	#define volume label and action menu/button
	echo '' > /tmp/pmount_${DEVNAME}_LABEL
	INVISLABEL=true
	MENU_BOOTMOUNT=false
	[ ! "`echo $ONEFS | grep -F ext`" ] && INVISLABEL=false
	if [ ! "$ONEMNTPT" ]; then
		INVISSHOWLOC=false
		INVISPIX=false
		INVISFILECHK=true
		echo false > /tmp/pmount_${DEVNAME}_domount
	else
		INVISSHOWLOC=true
		INVISPIX=true
		INVISFILECHK=false
		echo true > /tmp/pmount_${DEVNAME}_domount
	fi
	ACTION_MENU="
	<menuitem label=\"$(gettext 'Show location')\" stock=\"gtk-open\">
	 <variable>MENU_SHOWLOC_${DEVNAME}</variable>
	 <sensitive>${INVISSHOWLOC}</sensitive>
	 <action>rox -d ${ONEMNTPT} &</action>
	</menuitem>"
	if [ "$ONEFS" != "iso9660" ];then
		#check if patrition is mounted at boot
		[ "`grep "^mkdir -p /mnt/${DEVNAME}; mount" /etc/rc.d/rc.local | grep -F '#pmount'`" ] && MENU_BOOTMOUNT=true
		#---
		ACTION_MENU="$ACTION_MENU
		<menuitemseparator></menuitemseparator>
		<menuitem label=\"$(gettext 'Edit label')\" stock=\"gtk-edit\">
		 <sensitive>${INVISLABEL}</sensitive>
		 <action>volumelabel ${ONEDEV}</action>
		 <action>refresh:LABEL_${DEVNAME}</action>
		</menuitem>
		<menuitem label=\"$(gettext 'Check filesystem')\" stock=\"gtk-find\">
		 <variable>MENU_FILECHK_${DEVNAME}</variable>
		 <sensitive>${INVISFILECHK}</sensitive>
		 <action>rxvt --hold --title \"pMount - $(gettext 'Puppy Drive Mounter')\" -geometry 80x10 -bg black -fg green -e fsck -Cv \"$ONEDEV\"</action>
		</menuitem>
		<menuitemseparator></menuitemseparator>
		<menuitem checkbox=\"$MENU_BOOTMOUNT\" label=\"$(gettext 'Mount partition at boot')\">
		 <variable>MENU_BOOTMOUNT_${DEVNAME}</variable>
		 ${INVISBUT}
		 <action>cp -f /etc/rc.d/rc.local /tmp/pmount_tmp</action>
		 <action>if false grep -v '${DEVNAME} #pmount' /tmp/pmount_tmp > /etc/rc.d/rc.local</action>
		 <action>if true echo 'mkdir -p /mnt/${DEVNAME}; mount -t $ONEFS $ONEDEV /mnt/$DEVNAME #pmount' >> /etc/rc.d/rc.local</action>
		</menuitem>"
	fi
	BUTTON="
	<checkbox draw_indicator=\"false\">
	 <variable>BUTTON_${DEVNAME}</variable>
	 <label>$(gettext '(un) Mount')</label>
	 <default>$(</tmp/pmount_${DEVNAME}_domount)</default>
	 <input>cat /tmp/pmount_${DEVNAME}_domount</input>
	 ${INVISBUT}
	 <action>if false mountme UNMOUNT_${ONEDEV}_${ONEFS}_${ONEMNTPT}</action>
	 <action>if false disable:PIX_${DEVNAME}</action>
	 <action>if false disable:MENU_SHOWLOC_${DEVNAME}</action>
	 <action>if false enable:MENU_FILECHK_${DEVNAME}</action>
	 <action>if true mountme DOMOUNT_${ONEDEV}_${ONEFS}</action>
	 <action>if true enable:PIX_${DEVNAME}</action>
	 <action>if true enable:MENU_SHOWLOC_${DEVNAME}</action>
	 <action>if true disable:MENU_FILECHK_${DEVNAME}</action>
	 <action>if true buildpix \"${ONEPART}\" ${ONEDEV} ${ONECATEGORY}</action>
	 <action>if true refresh:PIX_${DEVNAME}</action>
	 <action>buildheading ${ONEDISK} ${ONECATEGORY} \"${ONEDISKDESCR}\"</action>
	 <action>refresh:PIX_DISK_${ONEDISKNAME}</action>
	</checkbox>"
	case "$ONEFS" in
		ntfs)
			if [ "`ntfslabel -f $ONEDEV 2> /dev/null`" ]; then ntfslabel -f $ONEDEV 2> /dev/null > /tmp/pmount_${DEVNAME}_LABEL; fi
			;;
		iso9660)
			if [ "`cddetect | grep -F 'cdtype: audio'`" ]; then 
				echo 'CD-Audio' > /tmp/pmount_${DEVNAME}_LABEL
				ACTION_MENU="<menuitem label=\"$(gettext 'Play')\" stock=\"gtk-media-play\"><action>defaultcdplayer &</action></menuitem>
				<menuitemseparator></menuitemseparator>
				<menuitem label=\"$(gettext 'Eject disc')\" stock=\"gtk-cdrom\"><action>eject ${ONEDEV} &</action><action type=\"exit\">REFRESH</action></menuitem>"
				ONEFS=cdda
				ONESIZE=74min
				BUTTON="<button><label>$(gettext '(un) Mount')</label><sensitive>false</sensitive></button>"
				INVISPIX=true
			else
				ACTION_MENU="${ACTION_MENU}
				<menuitemseparator></menuitemseparator>"
				[ "`pburn --help | grep -A10 -F '[MODE]' | grep -F info`" ] && ACTION_MENU="${ACTION_MENU}<menuitem label=\"$(gettext 'Disc information')\" stock=\"gtk-info\"><action>pburn -m info &</action></menuitem>"
				ACTION_MENU="${ACTION_MENU}
				<menuitem label=\"$(gettext 'Play') Video-DVD\" stock=\"gtk-media-play\"><action>defaultmediaplayer dvd:// &</action></menuitem>
				<menuitemseparator></menuitemseparator>
				<menuitem label=\"$(gettext 'Eject disc')\" stock=\"gtk-cdrom\"><action>eject ${ONEDEV} &</action><action type=\"exit\">REFRESH</action></menuitem>"
				[ "$ONEMNTPT" ] && INVISPIX=true
			fi
			;;
		vfat)
			if [  `mlabel -i $ONEDEV -s :: 2> /dev/null | cut -d " " -f 4` ]; then mlabel -i $ONEDEV -s :: 2> /dev/null | cut -d " " -f 5 > /tmp/pmount_${DEVNAME}_LABEL; fi
			;;
		ext*)
			e2label $ONEDEV 2> /dev/null > /tmp/pmount_${DEVNAME}_LABEL
			;;
		swap)
			echo Memory > /tmp/pmount_${DEVNAME}_LABEL
			export PIXTEXT="${ONESIZE}"
			BUTTON="<button><label>$(gettext '(un) Mount')</label><sensitive>false</sensitive></button>"
			if [ "`grep -Fw "$ONEDEV" /proc/swaps`" ]; then
				ACTION_MENU="<menuitem label=\"$(gettext 'Swap off')\" stock=\"gtk-no\"><action>swapoff $ONEDEV</action><action type=\"exit\">REFRESH</action></menuitem>"
				INVISPIX=true
			else
				ACTION_MENU="<menuitem label=\"$(gettext 'Swap on')\" stock=\"gtk-yes\"><action>swapon $ONEDEV</action><action type=\"exit\">REFRESH</action></menuitem>"
			fi
			;;
	esac

	buildpix "${ONEPART}" ${ONEDEV} ${ONECATEGORY}

	PARTSGUI="${PARTSGUI}
	<hbox height-request=\"22\">
	 <menubar><menu label=\"${DEVNAME}\" stock=\"gtk-arrow_down\">$ACTION_MENU</menu></menubar>
	 <text space-expand=\"false\" space-fill=\"false\"><variable>LABEL_${DEVNAME}</variable><input>cat /tmp/pmount_${DEVNAME}_LABEL</input></text>"
	 [ "$INVISBUT" ] && PARTSGUI="${PARTSGUI}<pixmap space-expand=\"false\" space-fill=\"false\"><input file>/usr/share/pixmaps/puppy/puppy.svg</input><height>20</height></pixmap>"
	 
	 PARTSGUI="${PARTSGUI}
	 <hbox space-expand=\"true\" space-fill=\"true\"><text><label>\"\"</label></text></hbox>
	 <text><label>${ONEFS}</label></text>
	 <vbox spacing=\"0\">
	  <text height-request=\"2\"><label>\"\"</label></text>
	  <pixmap><variable>PIX_${DEVNAME}</variable><sensitive>$INVISPIX</sensitive><input file>/tmp/pmount${DEVNAME}_svg</input></pixmap>
	 </vbox>
	 $BUTTON
	</hbox>
	<text height-request=\"2\"><label>\"\"</label></text>"
done
########################################################################
 PARTSGUI="${PARTSGUI}
  <text height-request=\"15\"><label>\"\"</label></text>
 </vbox>"
 OLDDISKNAME="$ONEDISKNAME"
done


if [ "$TABFLAG" = "on" ];then #v4.01
 PARTSGUI="${PARTSGUI}</vbox>"
fi

PREFSBUTTON='
<button space-expand="false" space-fill="false">
  '"`/usr/lib/gtkdialog/xml_button-icon preferences`"'
  <action type="exit">SETPREFS</action>
</button>'

m_03="$(gettext 'drive')"
m_04="$(gettext 'usbdrv')"
m_05="$(gettext 'optical')"
m_06="$(gettext 'card')"
m_07="$(gettext 'floppy')"
M_TABLIST=$(echo $TABLIST|sed -e "s/drive/$m_03/" -e "s/usbdrv/$m_04/" -e "s/optical/$m_05/" -e "s/card/$m_06/" -e "s/floppy/$m_07/")
if [ "$SINGLEFLAG" = "false" ];then #default
 NOTEBOOKHEAD="<notebook space-expand=\"true\" space-fill=\"true\" labels=\"${M_TABLIST}\">"
 NOTEBOOKTAIL="</notebook>"
else
 NOTEBOOKHEAD="<vbox scrollable=\"true\">"
 NOTEBOOKTAIL="</vbox>"
 PARTSGUI="`echo "$PARTSGUI" | sed  's/ scrollable="true"//g'`"
fi

export PMOUNTGUI='
<window title="pMount" icon-name="gtk-harddisk" default_height="'$HEIGHT'" default_width="'$WIDTH'">
<vbox>
  
 '${NOTEBOOKHEAD}'
 '${PARTSGUI}'
 <hbox homogeneous="true" space-expand="true" space-fill="true">
   <text use-markup="true" space-expand="true" space-fill="true"><label>"<span fgcolor='"'#821811'"'><b>'$(gettext 'DO NOT REMOVE MOUNTED MEDIA')'</b></span>"</label></text>
 </hbox>
 '${NOTEBOOKTAIL}'

  <hbox space-expand="false" space-fill="false">
    <button space-expand="false" space-fill="false">
      '"`/usr/lib/gtkdialog/xml_button-icon refresh`"'
      <label>'$(gettext 'Refresh')'</label>
      <action>writeconfig</action>
      <action type="exit">REFRESH</action>
    </button>
   '${PREFSBUTTON}'
   <button space-expand="false" space-fill="false">
     '"`/usr/lib/gtkdialog/xml_button-icon quit`"'
     <action>writeconfig</action>
     <action type="exit">EXIT</action>
   </button>
   '"`/usr/lib/gtkdialog/xml_scalegrip`"'
  </hbox>
 </vbox>
 <action signal="delete-event">writeconfig</action>
</window>'
echo "$PMOUNTGUI" > /tmp/pmountdlg.txt_${MYPID}
kill $X1PID

#gtk theme
echo 'pixmap_path "/usr/share/pixmaps/puppy/"
style "pmount"
{ stock["gtk-arrow_down"] = {{ "arrow_mini_down.svg", *, *, *}}
GtkStatusbar::shadow_type = GTK_SHADOW_NONE }
class "GtkWidget" style "pmount"' > /tmp/gtkrc_pmount
export GTK2_RC_FILES=/tmp/gtkrc_pmount:$HOME/.gtkrc-2.0

#v4.01...
[ ! -e /tmp/gtkdialog_pmount ] && ln -s /usr/sbin/gtkdialog /tmp/gtkdialog_pmount
/tmp/gtkdialog_pmount --file=/tmp/pmountdlg.txt_${MYPID} -G +"$X"+"$Y" >/tmp/pmountdlg_${MYPID} 2>/tmp/pmounterr




###################################################################################
#                                                                                 #
#                          P O S T   O P E R A T O I N S                          #
#                                                                                 #
###################################################################################

#[ -s /tmp/pmounterr ] && exit
#v412, no, do not exit if only a warning error msg...
if [ -s /tmp/pmounterr ];then
 #w477 running Xvesa: 'Xlib:  extension "Generic Event Extension" missing on display ":0.0".'
 [ "`grep -v -E 'WARNING|Generic Event Extension' /tmp/pmounterr`" != "" ] && exit
fi
rm -f /tmp/pmountdlg.txt_${MYPID}
#if gui killed by pup_eventd, then file will be empty. restart pmount...
if [ ! -s /tmp/pmountdlg_${MYPID} ];then
 rm -f /tmp/pmountdlg_${MYPID}
 exit
fi
RETPARAMS="`cat /tmp/pmountdlg_${MYPID}`"
eval "$RETPARAMS"

[ "$EXIT" = "REFRESH" ] && exec /usr/sbin/$PMOUNT $TOPACTUAL

if [ "$EXIT" = "SETPREFS" ];then
 DLGSETENG='
 <window title="pMount - '$(gettext 'Preferences')'">
 <vbox space-expand="true" space-fill="true">
   <frame '$(gettext 'Preferences')'>
     <text xpad="10" xalign="0" space-expand="true" space-fill="true"><label>'$(gettext "If you don't have many drives or partitions, you may find it more convenient to see everything in one window. Untick the box if you want the default tabbed interface, or tick for a single window.")'</label></text>
     <checkbox>
       <label>'$(gettext 'Tick box for single window')'</label>
       <default>'${SINGLEFLAG}'</default>
       <variable>NEWSINGLEFLAG</variable>
     </checkbox>
     <hseparator></hseparator>
     <text xpad="10" xalign="0" space-expand="true" space-fill="true"><label>'$(gettext 'If this checkbox is ticked, pMount will quit immediately after choosing to mount or unmount a partition. If you would prefer pMount to keep running afterward, then untick this box.')'</label><sensitive>false</sensitive></text>
     <checkbox>
       <sensitive>false</sensitive>
       <label>'$(gettext 'Tick for pMount to quit after mount/unmount')'</label>
       <default>'${PMOUNTQUIT}'</default>
       <variable>NEWPMOUNTQUIT</variable>
     </checkbox>
   </frame>
   <hbox>
     <button>
       '"`/usr/lib/gtkdialog/xml_button-icon cancel`"'
       <label>'$(gettext 'Cancel')'</label>
     </button>
     <button>
       '"`/usr/lib/gtkdialog/xml_button-icon ok`"'
       <label>'$(gettext 'Ok')'</label>
       <action>exit:OK</action>
     </button> 
   </hbox>
</vbox>
</window>'

 RETPARAMS="`echo "$DLGSETENG" | gtkdialog --stdin`"
 eval "$RETPARAMS"
 if [ "$EXIT" = "OK" ];then
  echo "$NEWSINGLEFLAG" > /root/.pmountsingle
  echo "$NEWPMOUNTQUIT" > /root/.pmountquit
 fi
 exec /usr/sbin/$PMOUNT $TOPACTUAL
fi

###END###
