#!/bin/sh
# 
# Gtkdialog box to burn CD or DVD using Wodim with basic options. Burnbox
# can burn ISO images, blank rewritable CD or create audio CD with WAV.
# 
# (c) - SliTaz GNU/Linux 2009 - GNU GPL v3

# Authors : Christophe Lincoln <pankso@slitaz.org>
#           Rohit Joshi <jozee@slitaz.org>
#
VERSION=20100315
TMPDIR="/tmp/burn-cd"

chk_install()
{	
	for pkg in $@
	do
		if [ ! -d /var/lib/tazpkg/installed/${pkg} ]; then
			UNINSTALLED="$UNINSTALLED $pkg"
		fi			
	done 
	if [ ! "$UNINSTALLED" = "" ] ; then
		xterm -geometry 80x16 -title "INSTALL PACKAGE" \
				-e "echo -n \"This option depends on $UNINSTALLED. Please install and try again..\"; sleep 4;"
	fi	
}

# Auto Install DEPENDS and/or SUGGESTED
install()
{
	#echo "pkgs to install: $1"
	for pkg in $1 ; do
	   # Avoid reinstall
		if [ ! -d /var/lib/tazpkg/installed/"$pkg" ]; then
			xterm -geometry 80x16 -title "INSTALL PACKAGE" \
				-e "	echo \"This option depends on $pkg. Installing $pkg as root: \" ;  subox tazpkg get-install $pkg --forced; sleep 2;
						echo -e \"----\nPress ENTER to close and PROCEED with decoding...\"; read i; exit 0;	"		
		fi
	done
	
}


# Check read write permission for device.
chk_rw_permissions()
{
	xterm -geometry 80x16 -title "Check Permission" \
		-e ' 
			if [ ! -r "$DEVICE"  -o   ! -w "$DEVICE" ]; then
				echo "You dont have read write permission for $DEVICE;  "
				echo "Add yourself to group cdrom: addgroup tux cdrom"								 		
			else
				echo "You have read write permission for $DEVICE. You can proceed to burn."					
			fi
			sleep 3;
		  '
}

# Display audio cd size.
audio_cd_stats()
{
	AUDIO_CD_SIZE=`du -m $TMPDIR | awk '{print $1}'`
	TRACK_NB=`ls -1 $TMPDIR | wc -l`
	echo -n "Total $TRACK_NB tracks: $AUDIO_CD_SIZE Mb"
}


decode_ogg()
{
	if ls $TMPDIR | grep -q .ogg; then
		cd $TMPDIR
		xterm -geometry 80x16 -title "Oggdec" \
			-e 'for i in *.ogg; do oggdec "$i" && rm "$i"; done; sleep 2'
	fi
}

decode_mp3()
{
	
	if ls $TMPDIR | grep -q .mp3; then
		cd $TMPDIR
		install "mpg123"
		
		xterm -geometry 80x16 -title "mpg123" \
				-e 'for file in *.mp3; do 
						mpg123 --rate 44100 --stereo --buffer 3072 --resync -w  `basename "$file" .mp3`.wav "$file" && rm -f "$file"; 
				  done; sleep 2'			  	
	fi
}

decode_video()
{
	# convert videos into a VCD/SVCD/DVD compatible mpg video format
	if ls $TMPDIR | grep -q ".avi\|.mov\|.wmv\|.flv"  ; then
		cd $TMPDIR
		install "ffmpeg"
				
		xterm -geometry 80x16 -title "ffmpeg" \
				-e ' echo -n "Select target type (pal-vcd ntsc-vcd pal-svcd ntsc-svcd pal-dvd ntsc-dvd) "; read TARGET_OPTIONS
					 for file in *.avi *.wmv *.mov *.flv; do
						 ext=`echo "${file##*.}"`
						 output_file=`basename "$file" .$ext`.mpg
					 	 ffmpeg -i "$file" -target "$TARGET_OPTIONS" "$output_file" && rm "$file";
					 done; sleep 2;
				   '
	fi
	

}

# convert spaces in filename with _ and remove special characters "()'&" {}\! and translate uppercase to lowercase
fix_filename()
{
	ls /tmp/burn-cd/* | while read file
	do
    	mv "$file" `echo $file | tr ' ' '_' | tr -d '[{}(),\!&]' | tr -d "\'" | tr '[A-Z]' '[a-z]' | sed 's/_-_/_/g' `
	done 
	
}

# We must think about " space " between directory/track and
# filter directory copy to avoid copying other files than audio.
# Only burning non-compressed wav format is supported directly.

copy_audio_file()
{
	if ls "$NEW_TRACK" | grep -q .ogg; then
		cp "${NEW_TRACK%.ogg}.ogg" $TMPDIR
		fix_filename	
		decode_ogg 
	elif ls "$NEW_TRACK" | grep -q ".[m\|M][p\|P]3"; then
	  #	cp "${NEW_TRACK%.mp3}.mp3" $TMPDIR	
		cp "$NEW_TRACK" "$TMPDIR"	
		fix_filename
		decode_mp3
	else
		cp "${NEW_TRACK%.wav}.wav" $TMPDIR
	fi
}


copy_audio_dir()
{
	
	for i in .wav .ogg .mp3
	do
		cp "$NEW_DIR"/*$i $TMPDIR 2>/dev/null
	done
	fix_filename 
	decode_ogg  
	decode_mp3 
}

# Only burning mpg video format is supported directly. MPEG-1 video for vcd and MPEG-2 for svcd and dvd
copy_video_file()
{
	if ls "$NEW_TRACK" | grep -q ".mpg\|.mpeg"; then
		cp "${NEW_TRACK%.mp*}.mpg" $TMPDIR
	elif ls "$NEW_TRACK" | grep -q ".avi\|.mov\|.wmv\|.flv"; then
	 	ext=`echo "${NEW_TRACK##*.}"`
		cp "${NEW_TRACK%.$ext}.$ext" $TMPDIR
		fix_filename
		if "$CHECKBOX_DECODE" ; then decode_video ; fi
	else
		echo "mpg format supported"
	fi
}

copy_video_dir()
{
	for i in .mpg .avi .mov .wmv .mpeg .flv
	do
		cp "$NEW_DIR"/*$i $TMPDIR 2>/dev/null
	done
	fix_filename 	
	if "$CHECKBOX_DECODE" ; then decode_video ; fi
}

copy_file()
{
	case "$BURN_MODE" in
			audio-cd) 
				copy_audio_file ;;
			vcd|svcd|video-dvd)
				copy_video_file ;;	
			*)	
				cp "$NEW_TRACK" $TMPDIR ; fix_filename ;;
	esac
	
}

copy_dir()
{
	case "$BURN_MODE" in
			audio-cd) 
				copy_audio_dir ;;
			vcd|svcd|video-dvd)
				copy_video_dir ;;	
			*)	
				cp "$NEW_DIR" $TMPDIR 2>/dev/null 
				fix_filename ;;
	esac		
}
# =====ISO=====
burn_iso()
{
	xterm -geometry 80x16 -title "Wodim" \
		-e "wodim -v speed=$SPEED dev=$DEVICE $OPTIONS '$ISO_IMAGE'; sleep 4			
		"
}
# =====AUDIO=====
# Use -pad to avoid file size error.
burn_audio()
{

	install "cdrkit"
	xterm -geometry 80x16 -title "Wodim:AUDIO" \
			-e " echo \"BURN TYPE SELECTED = $BURN_MODE \"; sleep 1;				
			 wodim -v speed=$SPEED dev=$DEVICE $OPTIONS -pad -dao -audio $TMPDIR/*.wav; sleep 4 
			 
		"
}
# =====DATA=====
burn_cddata()
{
	
	install "cdrkit"

	xterm -geometry 80x16 -title "Wodim:CD DATA" \
			-e " echo \"BURN TYPE SELECTED = $BURN_MODE \"; sleep 1;
				wodim -v speed=$SPEED dev=$DEVICE $OPTIONS -pad -dao -data $TMPDIR/*; sleep 4 
				
			"
				
}

burn_dvddata()
{
	# For multisession support, remove --dvd-compat option
	install "dvd+rw-tools"

	xterm -geometry 80x16 -title "growisofs:DVD DATA" \
			-e " echo \"BURN TYPE SELECTED = $BURN_MODE \"; sleep 1;
				# no iso-file available
				growisofs -dvd-compat -speed=$SPEED -pad -J -r -f -Z  $DEVICE  $TMPDIR/*; sleep 4	
				"
}

# ====VIDEO=====
burn_dvdvideo()
{

	install "dvd+rw-tools"
	
	# current assumption: compatible dvd-video format
	xterm -geometry 80x16 -title "growisofs:DVD VIDEO" \
			-e " echo \"BURN TYPE SELECTED = $BURN_MODE\"; sleep 1;    
			   	 growisofs -dvd-video -udf -pad -J -r -f -Z $DEVICE -speed=$SPEED  $TMPDIR/*; sleep 2
				"	
		
}

burn_vcd()
{
	
	install "vcdimager"

	mkdir -p $TMPDIR/vcd
		xterm -geometry 80x16 -title "vcdimager:VCD" \
			-e " echo \"BURN TYPE SELECTED = $BURN_MODE $UNINSTALLED \"; sleep 1;
			   	 vcdimager -t vcd2 -l VCD -c $TMPDIR/vcd/vcd.cue -b $TMPDIR/vcd/vcd.bin $TMPDIR/*.mpg; sleep 2; 
				# cdrdao write --device $DEVICE $TMPDIR/vcd/vcd.cue; sleep 2
				  wodim -v speed=$SPEED dev=$DEVICE $OPTIONS -pad -dao cuefile=$TMPDIR/vcd/vcd.cue ; sleep 2				
				"	
	
		
}

burn_svcd()
{
	
	install "vcdimager"

	mkdir -p $TMPDIR/svcd
		xterm -geometry 80x16 -title "vcdimager:SVCD" \
			-e " echo \"BURN TYPE SELECTED = $BURN_MODE\"
				  vcdimager -t svcd -l SVCD -c $TMPDIR/svcd/svcd.cue -b $TMPDIR/svcd/svcd.bin $TMPDIR/*.mpg; sleep 2; 
				 # cdrdao write --device $DEVICE $TMPDIR/svcd/svcd.cue; sleep 2;
				 wodim -v speed=$SPEED dev=$DEVICE $OPTIONS -pad -dao cuefile=$TMPDIR/svcd/svcd.cue ; sleep 2
				"	
	
}

# =====CLONE=====

rip_disc()
{
	SUGGESTED="cdrkit-isoinfo"
	if ! "$CHECKBOX_FOLDER" ; then SAVE_DISC="/tmp/burn-cd" ; fi	
	if [ -d /var/lib/tazpkg/installed/${SUGGESTED} ]; then
		xterm -geometry 80x16 -title "dd" \
			-e ' echo "RIPPING DISC $DEVICE AT $SAVE_DISC..."
				 COUNT=`isoinfo -d -i $DEVICE | grep "^Volume size is:" | cut -d " " -f 4`
				 BLOCK=`isoinfo -d -i $DEVICE | grep "^Logical block size is:" | cut -d " " -f 5`
				 dd if=$DEVICE of=$SAVE_DISC/image.iso bs=$BLOCK count=$COUNT; sleep 4
				 sleep 2;
				# eject ;
			   '
	else 
		xterm -geometry 80x16 -title "dd" \
			-e '   echo "Though you dont have the cdrkit-isoinfo package installed, \
				          you can still rip but it may be slower."
					echo -n "Would you like to continue (y/N)? : "; read ans
					if [ "$ans" = "y" ]; then 
						echo "RIPPING DISC $DEVICE AT $SAVE_DISC...."
						dd if=$DEVICE of=$SAVE_DISC/image.iso; 
						sleep 2;
						#eject ;
					fi
				'
	fi	
	if ! "$CHECKBOX_FOLDER" ; then 
				ISO_IMAGE="/tmp/burn-cd/image.iso"
				xterm -geometry 80x16 -title "dd" \
			-e ' echo -e " ---Please insert EMPTY DISC at $DEVICE ---\n ---press ENTER to continue..." && read close;'
				burn_iso
	fi
}

blank_dvd()
{
	xterm -geometry 80x16 -title "growisofs:DVD ERASE" \
		-e "growisofs -Z $DEVICE=/dev/zero"
}

burn_disc()
{
  	case "$BURN_MODE" in
			audio*)
				burn_audio ;;
			data-cd*)
				burn_cddata ;;
			data-dvd*)
				burn_dvddata;;
			video*)
				burn_dvdvideo;;
			vcd*)
				burn_vcd;;
			svcd*)
				burn_svcd;;			
	esac
		
}

track_list()
{
	for file in `ls $TMPDIR` ; do
		track_size=`du -m $TMPDIR/$file | awk '{print $1}'`
		echo "$file | $track_size"	
	done
}

export BIN=$0
# Main GTK interface
MAIN_DIALOG='
<window title="SliTaz - Burnbox" icon-name="drive-optical">
<vbox>

	<notebook labels=" Burn CD/DVD (Audio,Video,Data)| Backup Disc| Burn ISO | Help/Settings">
	
	<vbox>	
		<tree icon_name="audio-x-generic">
			<width>500</width><height>200</height>
			<variable>TRACKS_LIST</variable>
			<label>Track name (Double-click to remove a track) | Track Size (Mb)</label>
			<input>$BIN track_list</input>
			<action>rm "/tmp/burn-cd/$TRACKS_LIST"</action>
			<action>refresh:TRACKS_LIST</action>
			<action>refresh:TRACKS_SIZE</action>
		</tree>'
		
# Select burn audio-cd, data-cd, dvd-video or vcd/svcd		
MAIN_DIALOG=${MAIN_DIALOG}'
   <frame>
		  <hbox>
		   <text>
				<label> Select Burn type: </label>
			</text>
			<combobox>'
			tmp2="${MAIN_DIALOG}"
			for i in audio-cd data-cd data-dvd video-dvd vcd svcd; do
					[ "$i" = "$BURN_MODE" ] || tmp2="$tmp2<item>$i</item>"
			done
			tmp3='
			<variable>BURN_MODE</variable>						
			</combobox>
			<checkbox>
				<label> Enable decoding video</label>
				<variable>CHECKBOX_DECODE</variable>
				<default>true</default>											
			</checkbox>
			</hbox>
			'
MAIN_DIALOG="$tmp2$tmp3"
# Select, add and burn audio buttons.
MAIN_DIALOG=${MAIN_DIALOG}"
		<hbox>
			<text>
				<label> File:     </label>
			</text>
			<entry accept=\"filename\">
				<label>Select an Audio/Video/data track</label>
				<variable>NEW_TRACK</variable>
			</entry>
			<button>
			    <label>Browse</label>
				<input file stock=\"gtk-open\"></input>
				<action type=\"fileselect\">NEW_TRACK</action>
			</button>
			<button>
				<label>Add</label>
				<input file stock=\"gtk-add\"></input>
				<action>$0 copy_file</action>
				<action>refresh:TRACKS_LIST</action>
				<action>refresh:TRACKS_SIZE</action>				
			</button>
		</hbox>
		<hbox>
			<text>
				<label> Folder:</label>
			</text>
			<entry accept=\"directory\">
				<label>Select an Audio/Video/Data track</label>
				<variable>NEW_DIR</variable>
			</entry>
			<button>
			    <label>Browse</label>
				<input file stock=\"gtk-open\"></input>
				<action type=\"fileselect\">NEW_DIR</action>
			</button>
			<button>
				<label>Add</label>
				<input file stock=\"gtk-add\"></input>
				<action>$0 copy_dir</action>
				<action>refresh:TRACKS_LIST</action>
				
				<action>refresh:TRACKS_SIZE</action>
			</button>
		</hbox>"

MAIN_DIALOG=${MAIN_DIALOG}"
		<hbox>
			<text>
				<variable>TRACKS_SIZE</variable>
				<input>$0 audio_cd_stats</input>
			</text>
			<button>
				<label>Clean</label>
				<input file stock=\"gtk-clear\"></input>
				<action>rm -rf $TMPDIR/*</action>
				<action>refresh:TRACKS_LIST</action>
				<action>refresh:TRACKS_SIZE</action>
				<action>clear:NEW_TRACK</action>
				<action>clear:NEW_DIR</action>
			</button>
			<button>
				<label>Burn disc</label>
				<input file icon=\"forward\"></input>
				<action>$0 burn_disc</action>
			</button>
		</hbox>
		</frame>
	</vbox> "

# Backup CD
MAIN_DIALOG=${MAIN_DIALOG}'	
<vbox>	
	
		<text use-markup="true"> 
			<label>
			"
<b>Choose either the Data or the Audio CD backup frame </b>
"
		</label>
		</text> 
	
 <frame Data CD/DVD backup >
   <text>
		<label> 
			"  " 
		</label>
	</text>
			<checkbox>
				<label>Save backup on Hard Disk Folder (Unselect to backup on CD disc)</label>
				<variable>CHECKBOX_FOLDER</variable>
				<default>true</default>
				<action>if true enable:SAVE_DISC</action>
				<action>if true enable:OPENBUTTON</action>
				<action>if false disable:SAVE_DISC</action>
				<action>if false disable:OPENBUTTON</action>				
			</checkbox>
			<hbox>
				<text use-markup="true">
					<label>"      Backup Folder Path:"</label>
				</text>
				<entry accept="directory">
				<label>Select a folder to save cloned disc to</label>
					<variable>SAVE_DISC</variable>
				</entry>
				<button>
				    <label>Browse</label>
					<input file stock="gtk-open"></input>
					<variable>OPENBUTTON</variable>
					<action type="fileselect">SAVE_DISC</action>
				</button>	
				</hbox>				
'
# Burn backup button.
MAIN_DIALOG=${MAIN_DIALOG}"
			<hbox>
			<text>
				<label>\"Proceed to backup your data CD: \" 	</label>
			</text>
			<button>
					<label>Backup DataCD</label>
					<variable>DATA_RIP</variable>
					<input file icon=\"forward\"></input>
					<action>$0 rip_disc</action>
				</button>
			</hbox>
			</frame>"			
MAIN_DIALOG=${MAIN_DIALOG}'		
	<frame Audio CD backup>	
		<text>
			<label> 
				"  " 
			</label>
		</text> 			 				
			<hbox>
			<text>
				<label> "Proceed to clone your audio CD:"</label>
			</text>
				<button>					
				<label> Backup AudioCD</label>
				<variable>AUDIO_RIP</variable>
				<input file icon="forward"></input>
				<action>asunder</action>
				</button>
	        </hbox>
 </frame>
		
	</vbox>'
	
MAIN_DIALOG=${MAIN_DIALOG}'
	<vbox>
		<text use-markup="true"> 
			<label>
			"			 
			"
		</label>
		</text> 
		<frame Select ISO and burn>		
		<hbox>
		  <text>
		<label> 
			"  	" 
		</label>
		</text>
				<text use-markup="true">
					<label>"<b>ISO path:</b>"</label>
				</text>
				<entry>
					<variable>ISO_IMAGE</variable>
				</entry>
				<button>
				    <label>Browse</label>
					<input file stock="gtk-open"></input>
					<action type="fileselect">ISO_IMAGE</action>
				</button>
			</hbox>
			'
# Burn iso button.
MAIN_DIALOG=${MAIN_DIALOG}"
			<hbox>
				<button>
					<label>Burn ISO</label>
					<input file icon=\"forward\"></input>
					<action>$0 burn_iso</action>
				</button>
			</hbox>
			</frame>
			</vbox>"

	

#
#				
# tmp3=	
MAIN_DIALOG=${MAIN_DIALOG}'
	<vbox>
		<frame Information>
		
			<text width_request="250" use-markup="true">
				<label>
"Burnbox burns ISOs, backs up CD/DVDs, burns data CD/DVDs, audio CDs and video CDs (VCD/SVCD)
"
				</label>				
			</text>
			<hbox>
				<text use-markup="true">
					<label> "<b> Please consult HELP file if needed:  </b>"	</label>
				</text>
			  <button>
					<input file icon="help"></input>
					<action> browser file:///usr/share/doc/slitaz-tools/burnbox.html </action>
				</button>
				</hbox>
			
		</frame>
		<frame Settings>
		<text>
				<label>
"Before burning, please verify/change device writer settings below if needed.
"
				</label>
		</text>
		
			<hbox>
				<text use-markup="true">
					<label>"<b>Device:     </b>"</label>
				</text>
				<entry>
					<default>/dev/cdrom</default>
					<variable>DEVICE</variable>
				</entry>
			</hbox>
			<hbox>
				<text use-markup="true">
					<label>"<b>Speed:     </b>"</label>
				</text>
				<entry>
					<input>cat /proc/sys/dev/cdrom/info | grep "drive speed" | cut -f 3</input>
					<variable>SPEED</variable>
				</entry>
			</hbox>
			<hbox>
				<text use-markup="true">
					<label>"<b>Options:  </b>"</label>
				</text>
				<entry>
					<default>-eject -multi</default>
					<variable>OPTIONS</variable>
				</entry>
				<button>
					<input file icon="help"></input>
					<action>xterm -sb -geometry 95x25 -title "wodim help" -e "wodim --help ; echo -e \"----\nENTER to continue...\" && read close"</action>
				</button>
			</hbox>	'
			
	   MAIN_DIALOG=${MAIN_DIALOG}'		
		</frame>
		<frame Blank CD/DVD-RW>
			<hbox>
				<text use-markup="true">
					<label>"<b>Option:   </b>"</label>
				</text>
				<entry>
					<variable>BLANK_OPTS</variable>
					<default>fast</default>
				</entry>
				<button>
					<input file icon="help"></input>
					<action>xterm -geometry 80x16 -title "wodim blank=help" -e "wodim blank=help ; echo -e \"----\nENTER to continue...\" && read close"</action>
				</button>
				<button>
					<label>Blank disc</label>
					<input file icon="forward"></input>
					<action>xterm -title "Wodim" -e "wodim -v -blank=$BLANK_OPTS dev=$DEVICE; sleep 2"</action>
				</button>
			</hbox>
		</frame>
	</vbox>'
export MAIN_DIALOG=${MAIN_DIALOG}'
	
	</notebook>' 
	MAIN_DIALOG=${MAIN_DIALOG}"<hbox>
			<button>				
					<input file icon=\"dialog-information\"></input>
					<label> Check Permissions for Device</label>
					<action>$0 chk_rw_permissions</action>
				</button> 
				"
	MAIN_DIALOG=${MAIN_DIALOG}'
			<button>
			<label>Exit</label>
			<input file icon="exit"></input>
			<action type="exit">Exit</action>
		</button>
	</hbox>
	
</vbox>
</window>
'

# Script can be called with an arg to exec a function.
if [ -n "$1" ]; then
	$1
else
	mkdir -p $TMPDIR
	gtkdialog --center --program=MAIN_DIALOG >/dev/null
	rm -rf $TMPDIR
fi

exit 0
