#!/bin/zsh
#
# dyne:bolic software development kit - the commandline tool
#
# Copyright (C) 2003-2010 Denis "Jaromil" Roio <jaromil@dyne.org>
#
# with contributions and testing by:
#      2004          Alex Gnoli            <smilzo@sfrajone.org>
#                    Pierluigi Maori       <newmark@dyne.org>
#      2006          Aymeric Mansoux       <aym3ric@goto10.org>
#                    Antonios Galanopoulos <anton@goto10.org>
#      2010          Alessio Piffero       <fruity@freaknet.org>
#
# This source code is free software; you can redistribute it and/or
# modify it under the terms of the GNU Public License as published 
# by the Free Software Foundation; either version 3 of the License,
# or (at your option) any later version.
#
# This source code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# Please refer to the GNU Public License for more details.
#
# You should have received a copy of the GNU Public License along with
# this source code; if not, write to:
# Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

if [ -r /lib/dyne/utils.sh ]; then
  source /lib/dyne/utils.sh
else
  # standard output message routines
  # it's always useful to wrap them, in case we change behaviour later
  notice() { echo "[*] $1"; }
  act() { echo " .  $1"; }
  error() { echo "[!] $1"; }
fi
func() { if [ $DEBUG ]; then echo "[D] $1"; fi }

source /lib/dyne/modules.sh
source /lib/dyne/dialog.sh

PACKAGE="dyne:OS SDK"
VERSION="2.5"
if [ -z $DYNESDK ]; then
    # using export DYNESDK you can change this to what you like
    PFX="$DYNE_SYS_MNT/SDK"
else
  PFX=${DYNESDK}
fi

if [ -z $DYNESDK_GIT ]; then
    # using export DYNESDK_GIT you can change this to what you like
    DYNEGIT="$PFX/git/dyneII/"
else
    DYNEGIT=${DYNESDK_GIT}
fi


# get the SDK system version
if [ -r ${PFX}/cdrom/dyne/VERSION ]; then
  source ${PFX}/cdrom/dyne/VERSION
else
  source ${DYNE_SYS_MNT}/VERSION
fi

# generate the default name of the iso file
ISO=dyne-${DYNE_SYS_VER}.iso
# generate the default name of the ramdisk
INITRD=initrd

# define KRN for version of the kernel
if [ -z $KRN ]; then KRN=`uname -r`; fi

# define MODDIR for path to kernel modules
if ! [ $MODDIR ]; then
    if [ -x /mnt/usr/lib/modules ]; then
	MODDIR=/mnt/usr/lib/modules
    else MODDIR=/usr/lib/modules; fi
fi


notice "$PACKAGE version $VERSION   Software Development Kit"
act "by RASTASOFT AFRO LINUX   for the Freedom of Creation"

if ! [ -x /lib/dyne ]; then
  error "dyne shell libraries are not present on this system"
  error "can't run the dynesdk, use it inside dyne:II"
  exit 0
fi

OPTS=`getopt -o hvKp:o:s:m: -n 'dynesdk' -- "$@"`

FULL_RAMDISK=no

#eval set -- "$OPTS"

while true; do
    case "$1" in
	-h)
	    notice "SYNOPSIS: dynesdk [options] COMMAND"
            notice "OPTIONS:"
	    act "-h     print this help"
	    act "-v     print out the version of this tool"
	    act "-p     path to the SDK directory (default $DYNE_SYS_MNT/SDK)"
            act "-m     additional modules to add in ramdisk"
            act "-o     filename of the iso to generate (default dyne-VER.iso)"
            act "-s     sign generated iso with gpg ID"
	    act "-K     pack all kernel modules into the ramdisk"
	    act "       define kernel version in \$KRN (current is `uname -r`)"
            notice "MODULE DEVELOPMENT COMMANDS:"
	    act "mksdk      create an SDK environment inside the harddisk dock"
            act "mount      mount all unmounted SDK/modules in /opt"
            act "devel      extracts a module in SDK/modules and mount it RW"
	    act "squash     pack one or all the mounted modules in SDK/cdrom"
	    act "mkiso      pack the SDK/cdrom directory into a bootable iso"

	    notice "CORE DEVELOPMENT COMMANDS:"
	    act "mkinitrd   pack the initrd.gz into the SDK/cdrom"
	    act "mkusr      pack the dyne.sys in the SDK/cdrom"
            act "mkkern     pack the kernel and modules in the SDK/cdrom"
	    act "mkkern-src clean and pack kernel sources a new module"

	    echo; exit 2 ;;
	-v) exit 2 ;;
	-p) PFX=$2; shift 2 ;;
	-K) FULL_RAMDISK="yes"; shift 1 ;;
	-m) ADD_RAMDISK_MODULES=$2; shift 2 ;;
        -o) OUTPUT=$2; shift 2 ;;
        -s) SIGN=$2; shift 2 ;;
	--) shift; break ;;
	*)  CMD=$1; shift 1; break ;;
    esac
done

# function to check for required software
check_sw() {
    func "checking existance of $1"
    CHECK_SW="`which $1`"
    if [ -z $CHECK_SW ]; then
	error "$1 not found"
	RET=-1
    else
	func "$1 found in $CHECK_SW"
	RET=$CHECK_SW
    fi
}

check_sw git
if [ $? = -1 ]; then
    error "GIT is not found on the system"
    error "you need the devel.dyne module"
    error "freely available on ftp.dyne.org/dynebolic"
    error "or included in your DVD distribution"
    exit 0
fi

if [ "`whoami`" != root ]; then
    error "you must be ROOT on your machine to use the dyne SDK"
    exit 0
fi

if [ -z "$DYNE_SYS_MEDIA" ]; then
    error "it doesn't seems you are running dyne"
    error "in case you are, please set /boot/dynenv accordingly"
    exit 0
fi

if [ $DYNE_SYS_MEDIA = cdrom ]; then
    error "running from CDROM: you need to DOCK your system"
    error "copy the dyne/ directory into your harddisk"
    exit 0
fi

if ! [ -x $DYNE_SYS_MNT ]; then
    error "no dock found in ${DYNE_SYS_MNT}"
    error "please correct your DYNE environmental variables"
    error "this doesn't seems an usual dock, uh?"
    exit 0
fi

if [ "$CMD" != "mksdk" ]; then
  if ! [ -x $PFX/cdrom ]; then
    error "no dyne/SDK/cdrom directory found in ${PFX}/cdrom"
    error "you need to run 'dynesdk mksdk' first or fetch a cdrom skeleton"
    exit 0
  fi
fi
	
# if those are missing, the iso can't be packed
if [ -z $MKISOFS ]; then
    check_sw mkisofs;
    if [ $RET ]; then MKISOFS=$RET; fi
fi
if [ -z $MKSQUASHFS ]; then
    check_sw mksquashfs;
    if [ $RET ]; then MKSQUASHFS=$RET; fi
fi


########################################################################
### COMMAND FUNCTIONS
########################################################################

mksdk() {
  
  source $DYNE_SYS_MNT/VERSION
  notice "creating SDK inside $DYNE_SYS_MNT/dyne"
  act "version: sys $DYNE_SYS_VER - initrd $DYNE_INITRD_VER"
      
  mkdir -p ${PFX}
  cd ${PFX}

  ask_yesno 10 "Download dyne:II ramdisk skeleton files from online repository?"
  if [ $? = 1 ]; then
    act "checking out skeleton, please wait while downloading"
    if [ -x git ]; then
	cd git;
	git pull --rebase
	cd -;
    else
	git clone git://code.dyne.org/dynebolic.git git
    fi
  fi

  if ! [ -x sys ]; then
      
      ask_yesno 10 \
	  "I can uncompress dyne.sys, it will occupy approx 2Gb
 this way your /usr will become writable.\n
 You should do it only if you really need: it will make
 it harder to merge your modifications with upgrades to
 the main dyne core.\n\n
 Do you want to uncompress the dyne.sys ?"
      
      if [ $? = 1 ]; then
	  mkdir tmp
	  mkdir sys
	  act "uncompressing usr binaries from ${DYNE_SYS_MNT}/dyne.sys"
	  act "please wait, this operation requires long time..."
	  mount -o loop ${DYNE_SYS_MNT}/dyne.sys tmp
	  cp -rau tmp/* sys/
	  umount tmp
	  rm -r tmp
      fi
      
  else
      act "SDL/sys directory found"
      act "dyne.sys /usr filesystem is already uncompressed, skypping"
  fi
  
  ask_yesno 10 \
      "I can download the kernel sources, it will occupy approx 100MB
 this way you will be able to recompile the dyne:II kernel.\n
 You should do it only if you really need: compiling a kernel
 requires deep knowledge of Linux and in case you do anything
 wrong it might break your system.\n\n
 Do you want to download the dyne:II kernel sources ?"
  if [ $? = 1 ]; then
      act "downloading dyne:II kernel source and modules"
      rsync -P -r rsync.dyne.org::dynebolic-dev-anon/dyneII/kernel/ kernel
  fi

  if ! [ -x cdrom/isolinux/boot.cat ]; then
    act "using iso skeleton from /usr/share/dyne/cdrom"
    # build a SDK without online repository
    cp -ra /usr/share/dyne/cdrom .
  fi

  cd - > /dev/null

  notice "the SDK has been succesfully created!"
  echo
  act "if you need instructions, please refer to the online documentation"
  act "available at http://dev.dynebolic.org"
  act "happy hacking! ;)"
  echo
  
}

mountmods() {
    if ! [ $1 ]; then
        mount_sdk_modules
    else
        mount_sdk_modules $1
    fi
}


develone() {
    MOD=$1

    if ! [ -x /opt/${MOD} ]; then
        error "module $MOD is not mounted in /opt"
        return
    fi

    # check if module is in use
    lsof /opt/${MOD} > /dev/null
    if [ $? = 0 ]; then
        error "module is currently in use, operation aborted."
        return
    fi

    # check if module is already uncompressed in SDK
    if [ -x $PFX/modules/${MOD} ]; then
        error "a development version of the module is already present in your SDK"
        return
    fi

    MODSIZE=`du -hs /opt/$MOD | awk '{print $1}'`

    ask_yesno 10 \
"To extract the module $MOD in $PFX/modules will require $MODSIZE of space.\n\n
 Do you really want to proceed?" 
    if [ $? = 1 ]; then
      act "please wait while extracting files..."
      mkdir -p $PFX/modules/$MOD
      cp -ra /opt/$MOD $PFX/modules/
      umount /opt/$MOD
      mount -o bind $PFX/modules/$MOD /opt/$MOD
      add_module_path $MOD
      act "module $MOD succesfully converted to development mode"
    else
      act "operation aborted."
    fi
}


develmod() {

    if [ $1 ]; then

      develone $1

    else

      for mod in `ls --color=none /opt`; do

         develone ${mod}

      done

    fi

    act "modules were uncompressed in ${PFX}/modules"
}


squashone() {
    MOD=$1

    if ! [ -r ${PFX}/modules/${MOD} ]; then
        error "module ${MOD} doesn't exists in SDK"
        exit -1
    fi

    if ! [ -r ${PFX}/modules/${MOD}/VERSION ]; then
        error "module ${MOD} misses VERSION information: skipped"
        exit -1
    fi
	
    act "compressing ${PFX}/cdrom/dyne/modules/${MOD}"
    act "please wait, this may take a while..."

    act "updating locate database"
    mkdir -p ${PFX}/modules/${MOD}/var/lib
    updatedb --localpaths=${PFX}/modules/${MOD} --output=${PFX}/modules/${MOD}/var/lib/locatedb

    mkdir -p ${PFX}/cdrom/dyne/modules

    if [ -r ${PFX}/cdrom/dyne/modules/${MOD}.dyne ]; then
      rm ${PFX}/cdrom/dyne/modules/${MOD}.dyne
    fi

    # make the list of files to exclude
    EXCL="`find ${PFX}/modules/${MOD}/ -name .git`"

    $MKSQUASHFS "${PFX}/modules/${MOD}" "${PFX}/cdrom/dyne/modules/${MOD}.dyne" "-e" "${EXCL}"
    chmod a+r   ${PFX}/cdrom/dyne/modules/${MOD}.dyne
    chmod -x    ${PFX}/cdrom/dyne/modules/${MOD}.dyne

    act "done with ${MOD}"
    act "copy the module into your current dock to activate it:"
    act "cp ${PFX}/cdrom/dyne/modules/${MOD}.dyne $DYNE_SYS_MNT/modules"
 
}

squash() {
    notice "compressing the modules in the cdrom"
    if [ $1 ]; then

      squashone $1

    else

      for mod in `ls --color=none ${PFX}/modules`; do

        squashone ${mod}

      done

    fi

    chmod -x  $PFX/cdrom/dyne/modules/*.dyne
    chmod a+r $PFX/cdrom/dyne/modules/*.dyne

    act "modules were succesfully compressed in ${PFX}/cdrom/dyne/modules"
    ls -lh $PFX/cdrom/dyne/modules/*.dyne
}



mkinitrd() {
    notice "making the initrd compressed filesystem"

    # cleanup if needed
    if [ -x $PFX/initrd ]; then
        rm -rf $PFX/initrd
    fi
  
    mkdir -p $PFX/initrd
    cd $PFX/initrd

    act "creating the ramdisk filesystem"
    cp -ra /etc .

    mkdir lib
    cp -dp /lib/* lib/ 2>/dev/null 1>/dev/null
    cp -ra /lib/security lib/
    cp -ra /lib/udev lib/
    cp -ra /lib/dyne lib

    cp -ra /bin .
    cp -ra /sbin .
    mkdir -p boot dev proc root sys usr mnt home tmp
    # here copy the icon for the Volumes
    if [ -r /usr/share/icons/graphite/48x48/apps/disks.png ]; then
       cp -f /usr/share/icons/graphite/48x48/apps/disks.png mnt/.DirIcon
    fi
    ln -s /usr usr/share
    mkdir usr/lib
    ln -s /lib/security usr/lib/security
    ln -s /etc/terminfo usr/terminfo
    ln -sf /bin/zsh bin/sh
    mknod dev/console c 5 1
    mkdir dev/pts
    mkdir -p var/run
    # create a link for smbmnt so that it is found by mount
    mkdir -p usr/bin
    ln -s /sbin/smbmnt usr/bin/smbmnt
    echo "# Ramdisk version $DYNE_INITRD_VER" > boot/dynenv

    act "cleaning up configs and logs"
    rm -f etc/X11/XF86Config
    rm -f etc/X11/xorg.conf
    rm -f etc/HOSTNAME
    rm -f etc/hostname
    rm -f etc/NETWORK
    rm -f etc/LANGUAGE
    rm -f etc/auto.removable
    rm -f etc/blkid.tab*
    rm -f etc/fstab
    rm -f etc/mtab
    rm -f etc/resolv.conf*
    rm -f etc/asound.state
    rm -f etc/modprobe.conf
    rm -f etc/hosts
echo "127.0.0.1 localhost" > etc/hosts
cat << EOF > etc/resolv.conf
nameserver 216.254.95.2
nameserver 216.231.41.2
nameserver 62.108.1.65
nameserver 62.108.1.66
EOF

    rm -f boot/dynenv*
    touch boot/dynenv
    touch boot/dynenv.modules
    rm -f boot/mode
    echo "booting" > boot/mode
    # here windowmaker dock and menu is reset
    rm -f etc/WindowMaker/WMRootMenu
    rm -f etc/WindowMaker/WMState
 
    act "generating a fresh password file"
    rm -f etc/passwd
    cat <<EOF  > etc/passwd
root:x:0:0:root:/root:/bin/zsh
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
haldaemon:x:11:11:hal:/var/run:/bin/false
privoxy:x:13:13:proxy:/bin:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
sshd:x:100:65534::/var/run/sshd:/bin/false
luther:x:1000:1000:Luther Blissett guest account:/home/luther:/bin/zsh
EOF

    rm -f etc/shadow etc/shadow-
    cat <<EOF  > etc/shadow
root:\$1\$o9O/uypL\$T2M2X.zkz9KHL4sPgS9Oa.:13276:0:99999:7:::
distcc:x:12939:0:99999:7:::
nobody:x:12939:0:99999:7:::
sshd:!:12941:0:99999:7:::
exim:!:12941:0:99999:7:::
lp:!:12941:0:99999:7:::
luther:\$1\$Nmg1Xksd\$wXr2gr1vIeV0EizoIkb0Y1:12942:0:99999:7:::
EOF
    chmod go-rw etc/shadow
    chmod u-w etc/shadow

    rm -f etc/group
    cat <<EOF  > etc/group
root:x:0:
daemon:x:1:
nogroup:x:65534:
bin:x:2:
sys:x:3:
adm:x:4:
tty:x:5:
disk:x:6:
lp:x:7:
mail:x:8:
news:x:9:
uucp:x:10:
haldaemon:x:11:
man:x:12:
proxy:x:13:
kmem:x:15:
dialout:x:20:
fax:x:21:root,luther
voice:x:22:root,luther
cdrom:x:24:root,luther
floppy:x:25:root,luther
tape:x:26:root,luther
sudo:x:27:
audio:x:29:root,luther
operator:x:37:
list:x:38:
irc:x:39:
src:x:40:
shadow:x:42:
utmp:x:43:
video:x:44:root,luther
staff:x:50:
games:x:60:
users:x:100:root,luther
crontab:x:101:
ssh:x:103:
EOF
   
    act "generating a fresh filesystem table"
    cat << EOF > etc/fstab
# /etc/fstab: file system information, see man fstab
# on dyne this file is generated at runtime while booting
#
# <file system>	<mount point>   <type>  <options>       <dump>  <pass>
/dev/ramdisk	/		ext2	defaults	0	0
devpts		/dev/pts	devpts	defaults	0	0
proc            /proc           proc    defaults	0	0
sysfs		/sys		sysfs	defaults	0	0
usbfs		/proc/bus/usb	usbfs	defaults	0	0
EOF

    act "linking shared libraries in ramdisk"
    touch etc/ld.so.conf
    echo "/usr/lib" >> etc/ld.so.conf
    echo "/usr/X11R6/lib" >> etc/ld.so.conf
    ldconfig -f etc/ld.so.conf -C etc/ld.so.cache

    act "packaging /var"
    cp -ra /var .
    cleandir var/local
    cleandir var/cache
    cleandir var/lock
    cleandir var/tmp
    cleandir var/run
    cleandir var/log
    cleandir var/lib/rpm
    cleandir var/lib/locate
    mkdir -p var/log/hotplug var/log/login
    mkdir -p var/log/setup var/log/cups var/log/samba
    mkdir -p var/cache/samba var/cache/union
    mkdir -p var/local var/lock var/tmp
    mkdir -p var/run var/log var/lib/rpm
    mkdir -p var/spool/incron var/spool/cups
    mkdir -p var/log/icecast
    chown nobody:nogroup var/log/icecast

  
    if [ -x $DYNEGIT/startup ]; then
	act "setup startup files from subversion repository"
	cp -vf $DYNEGIT/startup/rc.*     etc/
	cp -vf $DYNEGIT/startup/zshenv   etc/
	cp -vf $DYNEGIT/startup/inittab  etc/
        for f in `ls -A $DYNEGIT/startup/bin/ | grep -v .git`; do
          cp -raf ${DYNEGIT}/startup/bin/${f}       bin
        done

        if [ -x ${DYNEGIT}/startup/lib ]; then
          # blank all lib/dyne
          rm -rf lib/dyne/*

	  for f in `ls $DYNEGIT/startup/lib/`; do
	      cp -raf ${DYNEGIT}/startup/lib/${f}       lib/dyne/
	  done

          mkdir -p lib/dyne/zsh
	  for f in `ls $DYNEGIT/startup/zsh/`; do
	      cp -af ${DYNEGIT}/startup/zsh/${f}        lib/dyne/zsh/
	  done

          mkdir -p lib/dyne/xdg
	  for f in `ls $DYNEGIT/startup/xdg/`; do
	      cp -raf ${DYNEGIT}/startup/xdg/${f}	lib/dyne/xdg/
	  done

          mkdir -p lib/dyne/skel
	  for f in `ls -A $DYNEGIT/startup/skel/ | grep -v .git`; do
	    cp -raf ${DYNEGIT}/startup/skel/${f}	lib/dyne/skel/
	  done

          mkdir -p lib/dyne/hotplug
          rm -f lib/dyne/hotplug/debug # no debug by default
          for f in `ls $DYNEGIT/startup/hotplug/`; do
            cp -raf ${DYNEGIT}/startup/hotplug/${f} lib/dyne/hotplug/
          done

          mkdir -p lib/dyne/udev
          for f in `ls $DYNEGIT/startup/udev/`; do
            cp -raf ${DYNEGIT}/startup/udev/${f}	lib/dyne/udev/
          done
          
          mkdir -p lib/dyne/configure
	  for f in `ls $DYNEGIT/startup/configure/`; do
	    cp -af ${DYNEGIT}/startup/configure/${f}  lib/dyne/configure/
            cp -f  ${DYNEGIT}/startup/configure/.DirIcon lib/dyne/configure/
	  done
        fi

	mkdir -p etc/WindowMaker
	for f in `ls $DYNEGIT/startup/GNUstep/`; do
	  cp -af  ${DYNEGIT}/startup/GNUstep/${f}   etc/WindowMaker/
        done

        # delete all backup files
        for f in `find lib/dyne -name '*~'`; do
          rm ${f}
        done
    fi

    if [ -r /etc/rc.local ]; then
	act "including /etc/rc.local startup settings"
	cp -f /etc/rc.local etc/
    fi

    ######## KERNEL MODULES


    
    act "setup boot kernel modules for ${KRN}"
    if [ $FULL_RAMDISK = "yes" ]; then

	act "including all"
	mkdir -p lib/modules/${KRN}
	cp ${PFX}/cdrom/dyne/linux-${KRN}.kmods lib/modules

    else
        act "minimum needed"
	echo -n ":: "
	mkdir -p boot/modules/${KRN}
	for m in `iterate $SUPPORTED_FS`; do
	    M=`find ${MODDIR}/${KRN}/ -name "${m}.ko"`
            if [ ${M} ]; then
		cp ${M} boot/modules/${KRN}/
		echo -n "${m} "
		bzip2 -9 boot/modules/${KRN}/${m}.ko
            else
		echo
		error "module ${m} not found in ${MODDIR}/${KRN}/"
            fi
	done
    # also the samba and usb-storage modules
	cp `find ${MODDIR}/${KRN}/ -name "smbfs.ko"` boot/modules/${KRN}/
	bzip2 -9 boot/modules/${KRN}/smbfs.ko
	echo -n "smbfs "
	cp `find ${MODDIR}/${KRN}/ -name "usb-storage.ko"` boot/modules/${KRN}/
	bzip2 -9 boot/modules/${KRN}/usb-storage.ko
	echo -n "usb-storage "
	cp `find ${MODDIR}/${KRN}/ -name "ehci-hcd.ko"` boot/modules/${KRN}/
	bzip2 -9 boot/modules/${KRN}/ehci-hcd.ko
	
	echo
	
    # copy any additional module specified on commandline
	if [ $ADD_RAMDISK_MODULES ]; then
	    act "adding extra modules selected on commandline"
	    for m in `iterate $ADD_RAMDISK_MODULES`; do
    		M=`find ${MODDIR}/${KRN}/ -name "${m}.ko"`
		if [ -r ${M} ]; then
		    cp ${M} boot/modules/${KRN}/
		    echo -n "${m} "
		    bzip2 -9 boot/modules/${KRN}/${m}.ko
		else
		    error "module ${m} not found"
		fi
	    done
	fi
	echo
	
#     if [ $ADD_NETWORK_MODULES ]; then
#       act "adding extra network modules for online boot"
#       for m in `lsmod | awk '{print $1}' | grep -v '^Module\|^ppp_\|^slhc'`; do
#         if [ -r ${MODDIR}/${KRN}/kernel/drivers/net/${m}.ko ]; then
#           cp -v ${MODDIR}/${KRN}/kernel/drivers/net/${m}.ko boot/modules/${KRN}/
#           bzip2 -9 boot/modules/${KRN}/${m}.ko
#         fi
#       done
#     fi

    fi

    act "cleaning up from .revision directories"
    for svn in `find . -name '.svn'`; do
      rm -rf ${svn}
    done
    for git in `find . -name '.git'`; do
      rm -rf ${git}
    done
    
    act "calculating ramdisk size:"
    dirsum .
    initrd_size=`du -s .| awk '{print $1}'`
    act "initrd filesystem occupation: ${initrd_size}"
    ramdisk_size=`echo "${initrd_size}.0 + 100.0" | bc | cut -d. -f1` 
    
    cd - > /dev/null
    cd $PFX

    # setup the name for the ramdisk
    if [ $OUTPUT ]; then INITRD=$OUTPUT; fi
	     
    act "generate device file of ${ramdisk_size}K"
    dd if=/dev/zero bs=1k count=${ramdisk_size} \
	| cbar -s ${ramdisk_size} -bl 1k -of cdrom/dyne/${INITRD} -de -nb -np
    # dd if=/dev/zero of=cdrom/dyne/$INITRD bs=1 count=${ramdisk_size}
    # size was hardcoded to 12000 in d:b 2.5

    act "formatting ramdisk filesystem"
    mke2fs -F -m 0 -i 1024 -L ramdisk cdrom/dyne/$INITRD
    act "populating ramdisk static file"
    mkdir -p tmp

    mount -o loop,rw -t ext2 cdrom/dyne/$INITRD tmp
    if [ $? != 0 ]; then
      error "mount of initrd filesystem failed, aborting"
      return
    fi

    cp -ra initrd/* tmp
    rm -r tmp/lost+found
    umount tmp
    rm -r tmp
    rm -rf initrd

    act "tuning filesystem"
    tune2fs -c 0 -i 0 cdrom/dyne/$INITRD
    rm -f cdrom/dyne/$INITRD.gz
    gzip -9 cdrom/dyne/$INITRD
    act "`stat cdrom/dyne/$INITRD.gz`"
    cd - > /dev/null
    sync
}

mkusr() {
    notice "preparing the /usr squashed filesystem"

    # copy the current dynesdk inside the new system
    cp -v $DYNEGIT/devel/dynesdk /usr/sbin/dynesdk

    ask_yesno 10 \
"Would you like to download an up-to-date device ID database from internet?"
    if [ $? = 1 ]; then
      mv /usr/share/pci.ids /usr/share/pci.ids.old
      mv /usr/share/usb.ids /usr/share/usb.ids.old
      wget -O - http://pci-ids.ucw.cz/pci.ids.bz2 | bunzip2 > /usr/share/pci.ids
      wget -O - http://www.linux-usb.org/usb.ids > /usr/share/usb.ids
      if [ -r /usr/share/usb.ids ]; then
        rm /usr/share/usb.ids.old
      else
        error "usb device ids not found online"
        mv /usr/share/usb.ids.od /usr/share/usb.ids
      fi
      if [ -r /usr/share/pci.ids ]; then
	rm /usr/share/pci.ids.old
      else
        error "pci device ids not found online"
	mv /usr/share/pci.ids.old /usr/share/pci.ids
      fi
    fi

    if [ -r $PFX/startup/xdg/dyne.xml ]; then
      cp $PFX/startup/xdg/dyne.xml /usr/share/mime/packages/
      update-mime-database /usr/share/mime
    fi

    act "updating locate database"
    updatedb --localpaths=/usr --output=/usr/var/lib/updatedb

    act "start compressing: `date`"
    act "(please wait, takes long!)"
    if [ -r $PFX/cdrom/dyne/dyne.sys ]; then
      rm $PFX/cdrom/dyne/dyne.sys
    fi
    $MKSQUASHFS /usr $PFX/cdrom/dyne/dyne.sys -root-owned
    chmod a+r $PFX/cdrom/dyne/dyne.sys
    chmod -x  $PFX/cdrom/dyne/dyne.sys
    act "end: `date`"
    act "`stat $PFX/cdrom/dyne/dyne.sys`"
    sync
}

mkkern() {
    # check we are in the kernel source
    if ! [ -r Makefile ]; then
	    error "run this command from the top directory of the Linux kernel source"
	    exit 1;
    fi

    # retrieve the version of the kernel source we are in
    # it is stored in the Makefile..

    KRN=`cat Makefile | awk '
    BEGIN { krn="" }
    /^VERSION/      { krn = krn $3 "." }
    /^PATCHLEVEL/   { krn = krn $3 "."}
    /^SUBLEVEL/     { krn = krn $3 }
    /^EXTRAVERSION/ { krn = krn $3 }
    END { print krn }'`-dyne

    notice "packing the kernel version $KRN"

    # compose the kernel file name removing all . or -
    krnfile="`echo ${KRN} | sed -e 's/\.//g' | sed -r 's/-//g' | cut -c 1-8`.krn"

    act "due to isolinux restrictions on filesystems (8.3 names)"
    act "your kernel filename is: $krnfile"


	act "searching for kernel image bytecode in current kernel tree: ./arch/`uname -i`/boot/bzImage"

        if [ -r "arch/`uname -i`/boot/bzImage" ]; then

            act "found kernel in current kernel tree"
            cp -v "arch/`uname -i`/boot/bzImage" ${PFX}/cdrom/dyne/${krnfile}

        elif [ -r ${DYNE_SYS_MNT}/${krnfile} ]; then

	    act "searching for kernel image bytecode in ${MODDIR}/${KRN}/build"

	    act "found ${krnfile} in dock"
	    cp ${DYNE_SYS_MNT}/${krnfile} ${PFX}/cdrom/dyne/
	    
	elif [ -x ${MODDIR}/${KRN}/build/arch ]; then
	    
	    vmlinuz="`find ${MODDIR}/${KRN}/build/arch -name '*zImage'`"
	    if [ $vmlinuz ]; then

		act "found: using $vmlinuz"
		cp ${vmlinuz} ${PFX}/cdrom/dyne/${krnfile}

	    else

		error "the kernel source is not yet compiled in the SDK"
		
	    fi
	    
	else
	    
		error "could not find any kernel version $KRN"
		
	fi


    if ! [ -r ${PFX}/cdrom/dyne/${krnfile} ]; then
	error "compile your kernel sources in $PFX/kernel"
	error "or provide one in ${DYNE_SYS_MNT}/${krnfile}"
	error "to change kernel version export \$KRN variable"
	error "operation aborted."
	exit 1;
    fi

    # now the modules, if they are not squashed
    modpack="$PFX/cdrom/dyne/linux-${KRN}.kmods"
    krnverabbr="`echo $krnfile | cut -d. -f1`"
    
    if ! [ -r ${modpack} ]; then

        act "temporary installation of modules in ${PFX}/tmp"
	mkdir -p ${PFX}/tmp
        INSTALL_MOD_PATH="${PFX}/tmp" make modules_install
        cp System.map ${PFX}/tmp

	act "calculating module dependencies"
	depmod -ae ${KRN} -F System.map --basedir ${PFX}/tmp
        
	act "linking sources and system map"
        cp System.map ${PFX}/tmp/lib/modules/${KRN}
        rm ${PFX}/tmp/lib/modules/${KRN}/build
        rm ${PFX}/tmp/lib/modules/${KRN}/source

        ln -sf /opt/kernel-src-${krnverabbr}/src/linux-${KRN} ${PFX}/tmp/lib/modules/${KRN}/build
        ln -sf /opt/kernel-src-${krnverabbr}/src/linux-${KRN} ${PFX}/tmp/lib/modules/${KRN}/source
	
	act "packing modules in ${modpack}"
	$MKSQUASHFS ${PFX}/tmp/lib/modules/${KRN} $modpack -all-root
	chmod a+r $modpack
	chmod -x  $modpack
        rm -rf ${PFX}/tmp
	act "`stat $modpack`"
	sync
    else
        act "kernel modules linux-${KRN}.kmods are already present in ${PFX}/cdrom/dyne"
    fi


}

mkkern-src() {
    notice "creating a .dyne module of current kernel sources"
    # and the kernel sources
    if [ -r $PFX/modules/kernel-src-${krnverabbr}/VERSION ]; then
	error "kernel source module already present in"
	error "$PFX/modules/kernel-src-${krnverabbr}"
	error "delete that for explicit substitution. operation aborted."
	exit 0
    fi

    if ! [ -r ./MAINTAINERS ]; then
	error "mkkern-src must be invoked inside the linux kernel source"
	error "enter your kernel source tree and execute this command inside"
	exit 0
    fi
 # we are in the kernel source tree
    
    act "making kernel source clean"
    make clean
    act "packing kernel sources in $krnverabbr (please wait patiently)"
    mkdir -p $PFX/modules/kernel-src-${krnverabbr}
    mkdir -p $PFX/modules/kernel-src-${krnverabbr}/etc
    mkdir -p $PFX/modules/kernel-src-${krnverabbr}/src
    mkdir -p $PFX/modules/kernel-src-${krnverabbr}/src/linux-${KRN}
    cp -ar . $PFX/modules/kernel-src-${krnverabbr}/src/linux-${KRN}/
    cat << EOF > $PFX/modules/kernel-src-${krnverabbr}/VERSION
name		Linux kernel sources
desc		packed the `date +%D` on `hostname`
version		${KRN}
url		http://kernel.org
packager	${USER}
EOF
    
    notice "kernel sources packages in ${PFX}/modules/kernel-src-${krnverabbr}"
    act    "launch 'dynesdk squash kernel-src-${krnverabbr}' to squash the module"
    
}
mkiso() {
    notice "making the dyneII ISO"
    echo "# Forged on `date` " \
    	| tee $PFX/cdrom/dyne/VERSION
    echo "# using `$MKISOFS --version` on `uname -srm`" \
    	| tee -a $PFX/cdrom/dyne/VERSION
    echo >> $PFX/cdrom/dyne/VERSION
    DYNE_SYS_VER="`cat /usr/etc/DYNEBOLIC`"
    echo "DYNE_SYS_VER=$DYNE_SYS_VER" | tee -a $PFX/cdrom/dyne/VERSION
#    echo "MD5: `md5sum $PFX/cdrom/dyne/dyne.sys`" | tee -a $PFX/cdrom/VERSION
#    echo >> $PFX/cdrom/VERSION
    DYNE_INITRD_VER="`cat /etc/DYNEBOLIC`"
    echo "DYNE_INITRD_VER=$DYNE_INITRD_VER" | tee -a $PFX/cdrom/dyne/VERSION
    if [ $SIGN ]; then
    # generate md5sum hashes and gpg signatures in separate files
      rm $PFX/cdrom/dyne/*.md5 2>/dev/null 1>/dev/null
      rm $PFX/cdrom/dyne/*.asc 2>/dev/null 1>/dev/null
      echo "please wait while generating md5 sums"
      md5sum $PFX/cdrom/dyne/dyne.sys > $PFX/cdrom/dyne/dyne.sys.md5
      md5sum $PFX/cdrom/dyne/initrd.gz > $PFX/cdrom/dyne/initrd.gz.md5
      echo "cryptographically signing the md5 sums"
      gpg -u $SIGN -b -a $PFX/cdrom/dyne/dyne.sys.md5
      gpg -u $SIGN -b -a $PFX/cdrom/dyne/initrd.gz.md5
    fi

    # setup the name for the iso
    if [ $OUTPUT ]; then ISO=$OUTPUT; fi

    act "checking if the CDROM is complete"
    # the RAMDISK
    if ! [ -r $PFX/cdrom/dyne/initrd.gz ]; then
      ask_yesno 360 \
        "ramdisk is missing, should i create a new one from the running system?
if you say NO we'll just use the current ramdisk in your dock (recommended if you don't know what this is all about)"
      if [ $? = 1 ]; then
        mkinitrd
      else  
        act "using current ramdisk"
        cp -v ${DYNE_SYS_MNT}/initrd.gz ${PFX}/cdrom/dyne/
      fi
    fi
    # the USR SQUASHED SYSTEM
    if ! [ -r $PFX/cdrom/dyne/dyne.sys ]; then
      ask_yesno 360 \
        "dyne.sys (/usr filesystem) is missing, should i create a new one from the running system?
if you say NO we'll just use the current dyne.sys in your dock (recommended if you don't know what this is all about)"
      if [ $? = 1 ]; then
        mkusr
      else
    #    act "using current dyne.sys"
    #    cp -v ${DYNE_SYS_MNT}/dyne.sys ${PFX}/cdrom/dyne/
      fi
    fi
    # the MODULES
    if ! [ -r $PFX/cdrom/dyne/modules ]; then
      act "copying dyne modules from current dock..."
      cp -rav ${DYNE_SYS_MNT}/modules ${PFX}/cdrom/dyne/
    fi 
    # the CONFIG
#    if [ -r $PFX/startup/dyne.cfg ]; then
#      act "updating dyne configuration from development subversion"
#      cp -a $PFX/startup/dyne.cfg ${PFX}/cdrom/dyne/dyne.cfg
#    fi
    if ! [ -r $PFX/cdrom/dyne/dyne.cfg ]; then
      act "copying dyne configuration from current dock"
      cp -a ${DYNE_SYS_MNT}/dyne.cfg ${PFX}/cdrom/dyne/dyne.cfg
    fi

    # create the boot configurations
    kernfile=`ls $PFX/cdrom/dyne/*.krn`
    kernfile=`basename $kernfile`
    echo "configuring to boot from kernel $kernfile"
    rm -f $PFX/cdrom/isolinux/isolinux.cfg
    cat <<EOF > $PFX/cdrom/isolinux/isolinux.cfg
default linux

prompt 1
timeout 100
f1 boot.msg
f2 debug.msg
f3 vesa.msg
f4 thincl.msg
f5 license.msg

label linux
	display boot.msg
	kernel /dyne/$kernfile
	append initrd=/dyne/initrd.gz root=/dev/ram0 rw load_ramdisk=1 prompt_ramdisk=0 ramdisk_start=0 max_loop=64 vga=791
EOF

    act "proceeding to pack the ISO image $ISO"
    $MKISOFS -o $PFX/$ISO -J -R -udf -m '.git' \
            -b isolinux/isolinux.bin -c isolinux/boot.cat \
            -no-emul-boot -boot-load-size 4 -boot-info-table \
	    $PFX/cdrom/
    act "`stat $PFX/$ISO`"
    sync
}

########################################################################
#### DOCUMENTATION EXTRACTION

authors() {
  notice "extracting authors information in $PFX/AUTHORS"
  cat $PFX/startup/lib/dyne.applist \
   | awk -F '|' '!/^#/ { print "<a href=\"http://"$5"\">" $1 "</a> by " $6 }' |sort|uniq \
   | grep -vi 'WEB|AUTH' | grep -vi www > $PFX/AUTHORS
  act "done, `wc -l $PFX/AUTHORS` entries"
  warning "edit the file by hand for correct formatting in your document (or use awk)"
}



case "$CMD" in
    # execute commands
    mksdk)    mksdk        ;;
    mount)    mountmods $@ ;;
    devel)    develmod  $@ ;;
    squash)   squash    $@ ;;
    mkiso)    mkiso        ;;
    authors)  authors      ;;
    
    mkinitrd) mkinitrd ;;
    mkusr)    mkusr    ;;
    mkkern)   mkkern   ;;
    mkkern-src) mkkern-src ;;

    *) error "command \"$CMD\" not recognized"
       act "try -h for help"
       ;;
esac

notice "bye."
exit 1

