#!/bin/sh
#=============================================================================
# VERSION : 0.3
# LICENCE : GPL
# PURPOSE : Knoppix CD Customizer 
# DATE    : 2003-03-15
# REVISION: 2003-03-21
# AUTHOR  : Hans-Achim Unger, Achim.Unger@web.de (xdialog-features)
# ORGINAL : (c) 3/2003 by Thomas Lange, lange@informatik.uni-koeln.de 
# USAGE   : knx-cdcust.sh 
# SW      : bash, xdialog, create_compressed_fs 
# SYSTEM  : GNU/LINUX
# INIFILE : $HOME/.knx-cdcust.rc 
#=============================================================================
# |[]{}\'{print $0}'
head -n 14 $0 | tail -n13
#=============================================================================
# grep "()" knx-cdcust.sh | awk -F"(" '{print $1}':
list_of_routines(){
read_readme
read_init_file 
set_work_partition
#commented_out
set_dir_files
read_cd
make_swap_file
knoppixcdiso2iso
knoppixiso2dir
rm_tmpiso
update_index
create_new_iso_1
edit_top_level_image
create_new_iso_2
umount_dirs
blank_cdrw
burn_cd
customizing
run_234
uncompress_iso
build_image
run_678
cleanall
automatic
save_config
#=== main ========================
easy_menu
#=== main ========================
}
This_is_an_ini_file(){
# 8< - - - - - - - - - - - -  - - - -  >8
# This is $HOME/.knx-cdcust.rc
WORKPART=/users
CDRW=0,1,0
CDRO=/dev/sr0
knoppixiso=$WORKPART/knx-cdcust/knoppix.2003-01-20.dd
newiso=$WORKPART/knx-cdcust/ungix.$(date -I).dd
# 8< - - - - - - - - - - - -  - - - -  >8
}
# mkmyknoppix
#
# (c) 3/2003 by Thomas Lange, lange@informatik.uni-koeln.de (Orginal)
# (c) 3/2003 by Hans-Achim Unger, Achim.Unger@Ing-Buero-Unger.de (GUI-Expansion)
# Universitaet zu Koeln
#
# This is free software; see the GNU General Public License version 2
# or later for copying conditions.  There is NO warranty.

# this script creates a new knoppix image with your local software
# You have to adjust the variable rmpacks if you want to remove more packages
# This script and the list for rmpacks is tested with knoppix version 3.2
#
# call: mkmyknoppix <orig knoppix ISO image> <my knoppix image>
# a fast filesystem on which many inodes will be created
fastdir=/knx-cdcust

# a not so fast directory; but it can also be =fastdir
slowdir=$fastdir
#slowdir=/knx-cdcust

export newtree=$fastdir/knoppix-tree
tmpiso=$slowdir/knoppix-dir.iso
newisodir=$slowdir/new-knoppix

#=============================================================
export DIALOG=Xdialog
INIFILE=$HOME/.knx-cdcust.rc
SWPSIZE=524288
SWPSIZE=786176
MINFREDISK=6000000
#-------------------------------------------------------------
read_readme() {
cat <<'EOF'>/tmp/$USER.$$

 KNoppiX-CDCUSTomizer script knx-cdcust.sh
 
 Version 0.2.1
 Changes  with  0.2.1:
 - Debug: if no plugins exist, the program does not chroot
 
 Changes with 0.2:
 - Filenames changed to knx-cdcust.sh for all files
 - Working directory is now .../knx-cdcust/.....
 - Mounts a partition automatically, if possible
 - Ini-file .knx-cdcust.rc can be saved
 - Works from KNOPPIX-CD
 
 This is beta software to customize your knoppix-cd

 This is free software; see the GNU General Public License version 2
 or later for copying conditions.  There is NO warranty.

 It has been tested with knoppix 3.1 2003-01-20 on DEBIAN Woody
 ###########################################################
 !!! *   It has never been tested on  a WIN-Partition  * !!!
 ###########################################################
 
 0) You must be root: sudo -su 
 
 1) You must have an already mounted writable partition with 6 GB free space!
     "mkdir /users && mount /dev/hdaX /users # X is your choise! "
     
 2) You must know how to customize DEBIAN, it just chroot's to dir!
 
 3) If a file custom.$0 exists, it ist executed to customize the system!
    This will be used instead of chroot  
    
 4) If there is an ini-file ~/.knx-cdcust.rc it will be used to set directories
    and filenames. See line 15 to 23 of this script for format. You may cut&paste
    is to  ~/.knx-cdcust.rc
 
 5) It need's X11 to run;-) of course!
 
 6) On an open-file dialog read the title!!!!!
     - the first filename asked is where you already have or want to store your CD-image
     - the second dialog asks you to enter a name for the new image
      
 It is based on a script by Thomas Lange, which I expanded with Xdialog and stuff.
  
 Achim Unger
 
 Send bug reports and suggestions to:
 achim.unger@web.de
 
EOF

$DIALOG --title "Cut & Paste !" --textbox "/tmp/$USER.$$" 0 0

}
#=== HAU ==========================================
read_init_file () {

. $INIFILE 

}
#======================================================================
set_work_partition() {

# Look wether there is a mounted partition with free space

echo "WORKPART=>$WORKPART<" 

test -z "$WORKPART" && WORKPART=$(df | grep dev | awk '{if ($4 > 6000000 )  print $6}')

# Look wether a hdpartition can be mounted
#commented_out()
{
test -z "$WORKPART" &&	{
	
	# Create Mountpoint
	WORKPART=/user; mkdir $WORKPART 2>/dev/null
	
	# Mount the next partition that is available
	for DEVICE in $( fdisk -l | egrep -i "Linux|Win" | tr -d '*'| \
                    grep -vi swap|sort -nrk 4|awk '{if ($4 > 6000000 )print $1}' )
	do
	      echo mount -o rw $DEVICE $WORKPART
	      mount -o rw $DEVICE $WORKPART 
	      if [ "$?" == 0 ]
	      			then
	  				  	FREESPACE=$(df | grep $WORKPART | awk '{print $4}')
	      			if [ "$FREESPACE" -gt "$MINFREDISK" ]
	      			then
	      				echo success: 
	      				df 
	      			fi
	      			else echo "Can not mount -o rw $DEVICE $WORKPART -trying next" 
	      			fi	      
			  	test -z "$DISKPART"  || (echo success: ;df ; exit)
	         echo " EXIT: WORKPART=>$WORKPART< " 
	done        
	}
}	

test -z "$WORKPART" && $DIALOG --title " E R R O R " --msgbox "NO Partition found! You better press ^C!" 0 0 && exit

cd $WORKPART
pwd
knoppixiso=$($DIALOG --stdout --title "Filename for CD-Image" --fselect $fastdir 0 0 )
newiso=$($DIALOG --stdout --title "Filename for Remastered Image" --fselect $fastdir 0 0 )
}
#======================================================================
set_dir_files(){

CDRW=$(cdrecord -scanbus | grep -i rw | awk '{print $1}')
test -z "$CDRO" && CDRO="/dev/sr0"
CDRO=$($DIALOG --stdout --title "CD-Reader Device"  \
                --inputbox "CD-Reader Device (/dev/sr0): " 0 0 "$CDRO" )
                
knoppixiso=$($DIALOG --stdout --title "Filename for CD-Image" --fselect $fastdir 0 0 )
newiso=$($DIALOG --stdout --title "Filename for Remastered Image" --fselect $fastdir 0 0 )
}
#======================================================================
read_cd(){

$DIALOG --title "Reading CD"  \
         --msgbox "THIS IS BETA SOFTWARE\nIt might overwrite files on your harddisk!\nInsert CD in $CDRO!" 0 0

test -d $WORKPART   ||  $DIALOG --title " ERROR" --msgbox "$WORKPART does not exist or is a file!" 0 0 
echo "test ! -d $WORKPART/$fastdir  &&  mkdir -p $WORKPART/$fastdir "
test ! -d $WORKPART/$fastdir  &&  mkdir -p $WORKPART/$fastdir 

dd if=$CDRO of=$knoppixiso bs=1024
 
#echo knoppixiso=$knoppixiso
#echo newiso=$newiso

}
#======================================================================
make_swap_file() {

# 1 GByte needed 
SWAP=$(free| grep -i Swap| awk '{print $2}')
test "$SWAP" -lt $SWPSIZE &&  (  \
    dd if=/dev/zero of=/$WORKPART/swapfile bs=1024 count=$SWPSIZE ;\
    /sbin/mkswap /$WORKPART/swapfile $SWPSIZE ;\
    /bin/sync;\
    /sbin/swapon /$WORKPART/swapfile  )
}
# -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
knoppixcdiso2iso() {

# create a directory tree containing the files of the knoppix image
    set -e   # very important!

    [ -f $knoppixiso ] || {
	$DIALOG --title " E R R O R " --msgbox "$knoppixiso not found" 0 0
	exit 99
    }

    mount -r -o loop $knoppixiso /mnt
    mkdir -p $newisodir
    tar --exclude KNOPPIX/KNOPPIX -C /mnt -cf - KNOPPIX   | tar -C $newisodir -xvf -
    extract_compressed_fs /mnt/KNOPPIX/KNOPPIX  > $tmpiso
    umount /mnt
}
# -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
knoppixiso2dir() {

    mount -r -o loop $tmpiso /mnt
    mkdir -p $newtree
    cd $newtree
    echo "Creating directory $newtree"
    tar -C /mnt -cf - . | tar -C $newtree -xf -
    umount /mnt
}
# -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
rm_tmpiso() {

    rm -f $tmpiso
}
# -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
update_index() {

    chroot $newtree bash -c "dpkg --configure -a"
    chroot $newtree bash -c "updatedb; update-dlocatedb"
}
# -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
create_new_iso_1() {

	touch  $newtree/etc/modules.conf $newtree/lib/modules/*/modules.dep  
	make_swap_file
    mkisofs -L -R -l -V "KNOPPIX ISO9660" -v -allow-multidot $newtree \
          | create_compressed_fs - 65536 > $newisodir/KNOPPIX/KNOPPIX
 
}
# -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
create_new_iso_2() {

	cd $newisodir
	BOOTIMG=boot.img
	test -f KNOPPIX/boot-de.img && BOOTIMG=boot-de.img
	
   test -f $newisodir/$newiso && rm $newisodir/$newiso 
   mkisofs -l -r -J -V "KNOPPIX modified $(date -I)" -hide-rr-moved -v -b KNOPPIX/$BOOTIMG -c KNOPPIX/boot.cat -o $newiso $newisodir
   echo "$newiso was made of directories $newisodir "

}
# -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
umount_dirs() {

    umount /mnt || true
    [ -f $newtree/proc/cpuinfo ] && umount $newtree/proc
    exit 0
}
#=== HAU ===========================================================
blank_cdrw(){
	cdrecord  -v dev=$CDRW blank=fast
}
#=== HAU ===========================================================
burn_cd(){
	cdrecord -v dev=$CDRW -eject speed=0 $newiso ; echo $newiso       
}
# -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
#=== HAU ===========================================================
customizing(){

	ls /proc/cmdline 2>/dev/null || mount -t proc /proc $newtree/proc 
	
	# exec custom.knx-cdcust.sh, if it exists
	echo "############################################################"
	echo "New filesystem is in :$newtree "
	echo "You may now change your system: apt-get install opera*"
	echo "Type <exit> to continue "
	echo "############################################################"
	echo "New filesystem is in :$newtree "
	
	ls  $(dirname $0)/*custom.$(basename $0) 2>/dev/null
	result=$?
	
	if [ "$result" = "1" ] ;	then
   	echo	chroot $newtree bash               
     	chroot $newtree bash               # That is always a good idea    
	else
  		for f in $(dirname $0)/*custom.$(basename $0)
    		do
    			echo executing $f
       		$f 
      	done
	fi

	cp -vpr /root/bin/* $newtree/usr/local/bin
	test $? = 0 && echo "/root/bin/* copied OK" 

}
#=== HAU ===========================================================
edit_top_level_image() {
	
	test -f $MYFILES/index.html  \
			&& cp -vp $MYFILES/index.html $WORKPART/knx-cdcust/new-knoppix/KNOPPIX
	
	cd $WORKPART/knx-cdcust/new-knoppix/KNOPPIX 
echo	cd $WORKPART/knx-cdcust/new-knoppix/KNOPPIX 

	test "$(hostname -f)" == "x9.hau.int" && rm  index_* knoblind.bat KNOPPIX-FAQ-??.txt  knoppix.sh~ rawrite2-readme.txt mkfloppy.bat rawrite2.exe KNOPPIX-FAQ.txt README_Security.txt knoppix-cheatcodes.txt  boot.img boot-en.img
	cp -pv $MYFILES/index.html $WORKPART/knx-cdcust/new-knoppix/KNOPPIX
}
#=== HAU ===========================================================
edit_boot_image() {
echo edit_boot_image
############# should be changed soon ############################
MYFILES=/user/knx-cdcust
################################################################
	test -d $WORKPART/knx-cdcust/mnt || mkdir $WORKPART/knx-cdcust/mnt 
	
	cd $WORKPART/knx-cdcust/new-knoppix/KNOPPIX/KNOPPIX
	
	mount -o loop boot-de.img  $WORKPART/knx-cdcust/mnt
	
	test -f $MYFILES/syslinux.cfg && cp -vp $MYFILES/syslinux.cfg $WORKPART/knx-cdcust/mnt/syslinux.cfg 
	xedit $WORKPART/knx-cdcust/mnt/syslinux.cfg

	cp -vp --backup=numbered $WORKPART/knx-cdcust/mnt/syslinux.cfg $MYFILES
	umount $WORKPART/knx-cdcust/mnt
}
#=== HAU ===========================================================
run_234(){

	test -d $WORKPART/knx-cdcust  || $DIALOG --title "E R O R R O R" --msgbox \
		"Dir $WORKPART/knx-cdcust not found! \n Execute optinon 0 in next menu! " 0 0 

	read_cd 
	make_swap_file 
	knoppixcdiso2iso 
	knoppixiso2dir 
	ls /proc/cmdline 2>/dev/null || mount -t proc /proc $newtree/proc 
	customizing 
}
#=== HAU ===========================================================
uncompress_iso(){
	knoppixcdiso2iso 
	knoppixiso2dir 
	ls /proc/cmdline 2>/dev/null || mount -t proc /proc $newtree/proc 
}
#=== HAU ===========================================================
build_image(){
	ls /proc 2>/dev/null && umount $newtree/proc 
	update_index 
	create_new_iso_1
	echo " R E A D Y : $newiso/KNOPPIX" 
	$DIALOG --title " R E A D Y :-)) " --msgbox "$newiso" 0 0  &
}
#=== HAU ===========================================================
run_678(){
	ls $newtree/proc/cmdline 2>/dev/null  && umount $newtree/proc 
	update_index 
	create_new_iso_1
	create_new_iso_2
	blank_cdrw 
	burn_cd 
}  
#=== HAU ===========================================================
cleanall(){
	
	echo "swapoff $WORKPART/swapfile; rm $WORKPART/swapfile; rm -rf  $WORKPART/knx-cdcust" 
 
	TMPFILE=/tmp/$USER.$$
	echo  "   ###################################"   > $TMPFILE
	echo  "   #To clean up start a shell and do:#"   >> $TMPFILE
	echo  "   #      or cut & paste this        # "   >> $TMPFILE
	echo  "   ###################################"   >> $TMPFILE
	echo  "   swapoff $WORKPART/swapfile"         >> $TMPFILE
	echo  "   rm      $WORKPART/swapfile"         >> $TMPFILE
	echo  "   rm -rf  $WORKPART/knx-cdcust"       >> $TMPFILE

	$DIALOG --title "Remove all files including swap!" --textbox "$TMPFILE"  20 45
	rm $TMPFILE 
	
#   swapoff $WORKPART/swapfile; rm $WORKPART/swapfile ; rm -rf  $WORKPART/knx-cdcust" 
}
#=== HAU ===========================================================
save_config(){

	echo "WORKPART=$WORKPART"      >  $HOME/.knx-cdcust.rc
	echo "CDRW=$CDRW"              >> $HOME/.knx-cdcust.rc
	echo "CDRO=$CDRO"              >> $HOME/.knx-cdcust.rc
	echo "knoppixiso=$knoppixiso"  >> $HOME/.knx-cdcust.rc
	echo "newiso=$newiso"          >> $HOME/.knx-cdcust.rc
}
#=== HAU ===========================================================
auto_customizing(){
AUTONAME=auto-custom 

 test -f $(dirname $0)/$AUTONAME.$(basename $0) \
	&& . $AUTONAME.$(basename $0)

}
#=== HAU ===========================================================
automatic()
{
	read_cd
	uncompress_iso
	auto_customizing
	build_image
	edit_top_level_image;edit_boot_image
	blank_cdrw
	burn_cd
}
#=== HAU ===========================================================
easy_menu()
{
	test -x $(dirname $0)/custom.$(basename $0)  \
            &&  custom_menu="start $(dirname $0)/*custom.$(basename $0)" \
            ||  custom_menu="Chroot to $newtree"
            
   x=A         
	while true
	do
	A=$($DIALOG --stdout  --default-item "$x"  --menubox \
         "R E M A S T E R I N G - K N O P P I X"  25 110 0 \
	R "README" \
	0 "Partition is <$WORKPART> and orginal <$knoppixiso> and new <$newiso>" \
	A "Execute all A? in one go and enter C" \
	" A1" "Dumping CD $CDRO to $knoppixiso" \
	" A2" "Uncompress iso $knoppixiso to $newtree" \
	"B  " "$custom_menu  " \
	"C  " "Execute all C? in one go" \
	" C1" "Make an ISO image $newiso/KNOPPIX/KNOPPIX from filesystem <$newtree>" \
	x "Edit top level directory of image <$newiso> like generating <$newiso/KNOPPIX/knoppix.sh>" \
	" C2" "Make an ISO image <$newiso> from filesystem <$newisodir/KNOPPIX>" \
	" C3" "Blank CD cdrecord dev=$CDRW ..." \
	" C4" "Burn image $newiso to CD" \
	D "HOWTO: Remove all files including swap!" \
	E "Save settings form 0 in $HOME/.knx-cdcust.rc" \
	X "THE END" )
	
test $? -eq  1  && exit
        
   case $A in
  
   R) read_readme        ;x=A ;;
   0) set_dir_files      ;x=A ;;
   A) run_234            ;x=B ;;
	" A1") read_cd            ;x=" A2" ;;
	" A2") uncompress_iso     ;x="B  " ;;
	"B  ") customizing        ;x="C  " ;; 
	"C  ") run_678            ;x=D ;;
	" C1") build_image        ;x=x ;;
	x) edit_top_level_image;edit_boot_image  ;x=" C2" ;;
	" C2") create_new_iso_2  ;x=" C3" ;;
	" C3") blank_cdrw         ;x=" C4" ;;
	" C4") burn_cd            ;x=D ;;
	D) cleanall           ;x=E ;;
	E) save_config           ;x=X ;;
	X) exit ;; 
	esac
	
	done
}
#============= MAIN ==========================================
whereis create_compressed_fs | grep "/" || echo "Programm create_compressed_fs not found"
whereis Xdialog              | grep "/" || echo "Programm Xdialog not found"
whereis cdrecord             | grep "/" || echo "Programm cdrecord not found"

#===========================================
# Set some variables
#
 if [ -f $INIFILE ]
 then 
	read_init_file
	test -d $(dirname $newiso)  || mkdir -p $(dirname $newiso)
	test -d $(dirname $newtree) || mkdir -p $(dirname $newtree)
	newtree=$WORKPART/$newtree
	tmpiso=$WORKPART/$tmpiso
	newisodir=$WORKPART/$newisodir
	slowdir=$WORKPART/$slowdir
	fastdir=$WORKPART/$fastdir
else
	set_work_partition
	newtree=$WORKPART/$newtree
	tmpiso=$WORKPART/$tmpiso
	newisodir=$WORKPART/$newisodir
	slowdir=$WORKPART/$slowdir
	fastdir=$WORKPART/$fastdir
	set_dir_files  
fi

test -z "$NODISCLAIMER" && $DIALOG -title $0 --msgbox "D I S C L A I M E R !\n \
\n \
  This is  $(basename $0)  \n \
  It is still BETA \n \
  It might overwrite files on your harddisk,\n \
  drown your cat and seduce your girlfriends,\n \
  and, most important, trash your NON-LINUX-Partition!\n \
\n\
  ***************************************************************************************
  ***** READ TITLE OF NEXT WINDOWS FOR MEANING of FILENAMES *****
  ***************************************************************************************
\n\
 This is free software; see the GNU General Public License version 2\n \
 or later for copying conditions.  THERE IS NO WARRANTY!\n" 0 0

if [ "$1" == "automatic"  ]
 then 
	automatic
else
	easy_menu
fi
#============= MAIN ==========================================
