#!/bin/bash

# by default only write_partition is compiled and installed
# The toplevel makefile will call the functions ml_make_image(),ml_install_device(), ml_install_zero(),
# ml_install_file() and ml_install_new() directly
FUNCTIONS="findfiles installconfig configure compile installlocal"
EXECUTE_ALWAYS="$EXECUTE_ALWAYS make_image install_device install_zero install_file install_new"
STATISTICS=no
CLEANIMAGE_OPTIONS="PACKED PACKED_IMAGES"


if [ "$ID" != "" ] ; then
        INSTALL_DEVICE=$ID
fi 

opt_zero=0

function ml_configure() {
        :
}

function ml_compile() {
        ml_required_package cramfs
        ml_required_package packcramfs
        ml_required_package zlib

	cd $PACKAGE
	PATH=${ORIGPATH} $JMAKE GCC=gcc CC=gcc AS=as LD=ld CFLAGS= LDFLAGS= -C src local
	$JMAKE TARGETCC="$GCC" TARGETAS=as TARGETLD=ld CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS" -C src target
}

function ml_installlocal() {
        cd $PACKAGE
	cp src/write_partition $TOOLS/bin
	cp src/elfcat $TOOLS/bin
	cp elvenkind $TOOLS/bin
	cp src/write_partition.ml $TARGET/write_partition
}

# store a file inside anotherone, don't write blocks of '\0'
# $1=output file
# $2=input file
# $3=partition
function store_file() {
    offset=0
    if [ "$3" != 0 ] ; then
	start=`sed -n "s/.*disk$3[ *]*\([0-9]\+\).*/\1/p" ${1}_geometry`
	start=$(($start - 1))
	offset=$(($start * $DISK_SECTORS * 512))
    fi
    perl -e 'open(F, "+<$ARGV[0]") || die "cannot open $ARGV[0] for updating: $!\n";
             open(I, $ARGV[1]) || die "cannot open $ARGV[1] for reading: $!\n";
             sysseek(F, $ARGV[2],0) || die "seek failed on $ARGV[0]: $!\n";
             while(sysread(I, $b, 1024)) { 
                    if($b eq "\0" x 1024) {  
                           sysseek(F,1024,1); 
                    } else { 
                           syswrite(F, $b, length($b)); 
                    } 
             }' $1 $2 $offset
}

# resize a file (making it larger) by seeking to the requested size
# and writing one byte
# $1=file
# $2=new size (must be bigger that current size)
function resize_file() {
        perl -e 'open(F,"+<$ARGV[0]") || die "cannot open $ARGV[0] for updating: $!\n";
                 sysseek(F,$ARGV[1]-1,0);syswrite(F,"\0",1);close(F);' $1 $2
}

# Resize a packcramfs file (make it larger only)
# $1=disk image
# $2=packcramfs image
# $3=partition
function resize_packcramfs() {
    start=`sed -n "s/.*disk$3[ *]*\([0-9]\+\).*/\1/p" ${1}_geometry`
    end=`sed -n "s/.*disk$3[ *]*[0-9]\\+[ ]\+\([0-9]\+\).*/\1/p" ${1}_geometry`
    size=$(($end - $start))
    size=$(($size * $DISK_SECTORS * 512))
    fsize=`ls -l $2 | awk '{ print $5 }'`
    if [ $size -lt $fsize ] ; then
        echo "image $2 is too large"
        exit 1
    elif [ $size -gt $fsize ] ; then
        resize_file $2 $size
        packcramfs -C -w --resize $2
    fi
}

# calculate an md5sum of a directory 
# (uses name, size, permissions of all files and directories)
function calcmd5sum() {
        find $PARTS/$1 -type f | sort | xargs md5sum > $IMAGE/$1.md5sum.n
        find $PARTS/$1 -ls | perl -ane 'print "$F[10] $F[2] $F[6]\n";' | sort | md5sum >> $IMAGE/$1.md5sum.n
}

# check if the size of the images fit
# $1: max size of block device
function ml_check_size() {
        size=$1
        root_size=`ls -l $IMAGE/root1.img.cram | awk '{print 1+int($5/1000) }'`
        real=$root_size
        if [ "$ROOT_SIZE" = 0 ] ; then
            root_size=$(($root_size + $ROOT_FREE / 1000))
        else
            t=$(($root_size + $ROOT_FREE / 1000))
            r=$(($ROOT_SIZE / 1000))
            if [ $t -gt $r ] ; then
                echo "THERE IS NOT ENOUGH FREE SPACE ON THE ROOT PARTITION, ABORTING"
                exit 1
            fi
            root_size=$r
        fi
        root_size1=$root_size
        root_size2=$root_size

        if [ "$TEST_CLIENT_SRC" != "" -a "$TEST_CLIENT_SRC" != no ] ; then
                root_size1=$(($real + 10 ))
        fi

        rw_size=$((1 + $RWSIZE / 1000))


        ALL_IMAGES="$IMAGE/root1.img.cram $IMAGE/root2.img.cram $IMAGE/main.img.packed"
        all_size=`ls -l $ALL_IMAGES | awk '{ k+=$5 } END { print int(k/1000) }'`

        if [ $(($size / 2)) -lt $(($all_size + $rw_size )) ] ; then
            echo "THE INSTALL IMAGE IS LARGER THAN THE TARGET DRIVE, ABORTING"
            exit 1
        fi
}

# this feeds fdisk and should make partitions just large enough
# to fit their contents, with the exception of the last partition,
# which will take all the rest of the space.
ml_create_fdisk() {
        fdisk_script="n
p
1

+${root_size1}K
n
p
2

+${root_size2}K
n
p
${CONFIG_PARTITION}

+${rw_size}K
n
p
${PACKED_PARTITION}


a
1
p
w"
}

function ml_install_device()  {
        ### do size-related calculations and checking
        # size in 512-byte blocks
        OUTPUT=$INSTALL_DEVICE

        # The USB flash writer fails the first time it accesses the devices, so
        # this will do a quick read from it.  If that fails, then the '|| true'
        # will allow us to continue on our way, and it should read/write fine.
        dd if=$OUTPUT of=/dev/null count=1 || true

        ml_check_size $((`fdisk -s $OUTPUT` * 2))
        ml_create_fdisk
    
        echo "writing disk ... "

        # paranoia check
        if grep -q $OUTPUT /proc/mounts; then
                echo "$OUTPUT is mounted; will not install here!" 1>&2
                exit 1
        fi

        if [ $opt_zero = "yes" ]; then
                # zero the device (already done if it's a file)
                echo "zeroing device $OUTPUT"
                dd if=/dev/zero of=$OUTPUT || true
        else
                # otherwise just delete the partition table
                dd if=/dev/zero of=$OUTPUT bs=512 count=1
        fi

        echo "$fdisk_script" | fdisk $OUTPUT

        write_partition -q -p $TARGET/newmbr.bin ${OUTPUT}
        write_partition -q -p $IMAGE/root1.img.cram ${OUTPUT}1
        if [ -f $IMAGE/config.image ] ; then
                write_partition -q -p $IMAGE/config.image ${OUTPUT}${CONFIG_PARTITION}
        fi
        if [ "$TEST_CLIENT_SRC" = "" -o "$TEST_CLIENT_SRC" = no ] ; then
                write_partition -q -p $IMAGE/root2.img.cram ${OUTPUT}2


                # install packed version
                write_partition -q -p $IMAGE/main.img.packed ${OUTPUT}${PACKED_PARTITION}
                packcramfs -C -P -w --fast --resize ${OUTPUT}${PACKED_PARTITION}
        fi

        sync; sync; sync
        echo "done -- wait until flash activity light is off"
}

function ml_install_zero() {
        opt_zero=yes
        ml_install_device
}

function ml_install_disk() {
        OUTPUT=$DISK_FILENAME
        ml_check_size $(($DISK_HEADS * $DISK_SECTORS * $DISK_CYLINDERS))
        ml_create_fdisk

        echo "writing file ... "

        [ ! -f $OUTPUT ] || rm $OUTPUT
        # create the image
        touch $OUTPUT
        resize_file $OUTPUT $(($size*512))

        # prepend geometry to the fdisk script
        fdisk_script="x
h
$DISK_HEADS
c
$DISK_CYLINDERS
s
$DISK_SECTORS
r
$fdisk_script"

        echo "$fdisk_script" | fdisk $OUTPUT > ${OUTPUT}_geometry || true

        store_file $OUTPUT $TARGET/newmbr.bin 0
        store_file $OUTPUT $IMAGE/root1.img.cram 1
        store_file $OUTPUT $IMAGE/root2.img.cram 2

        if [ -f $IMAGE/config.image ] ; then
                store_file $OUTPUT $IMAGE/config.image $CONFIG_PARTITION
        fi

        # install packed version
        resize_packcramfs $OUTPUT $IMAGE/main.img.packed $PACKED_PARTITION
        store_file $OUTPUT $IMAGE/main.img.packed $PACKED_PARTITION

        echo "done"
}

function ml_install_new() {
        # paranoia check
        if grep -q $INSTALL_DEVICE /proc/mounts; then
            echo "$INSTALL_DEVICE is mounted; will not install here!" 1>&2
            exit 1
        fi
        $SCRIPTS/mlz mlinstall upto installlocal

        # The USB flash writer fails the first time it accesses the devices, so
        # this will do a quick read from it.  If that fails, then the '|| true'
        # will allow us to continue on our way, and it should read/write fine.
        dd if=$INSTALL_DEVICE of=/dev/null count=1 || true

        # find the active boot partition and install on the other one,
        # unless its a regression test system. In this case flash both roots

        if [ "$REGRESSION_TEST" = yes ] ; then
                ned=`packcramfs -p -I -q $IMAGE/root1.img.cram | sed 's/edition \([0-9]*\) .*/\1/'`
                for a in 1 2 
                do
                        oed=`packcramfs -p -I -q ${INSTALL_DEVICE}$a | sed 's/edition \([0-9]*\) .*/\1/'`

                        if [ "$ned" != "$oed" ] ; then 
                                write_partition -p $IMAGE/root$a.img.cram $INSTALL_DEVICE$a
                        fi
                done
                make_active $INSTALL_DEVICE 1
        else
                a=`make_active $INSTALL_DEVICE`
                n=`expr 3 - $a`

                ned=`packcramfs -p -I -q $IMAGE/root1.img.cram | sed 's/edition \([0-9]*\) .*/\1/'`
                oed=`packcramfs -p -I -q ${INSTALL_DEVICE}$a | sed 's/edition \([0-9]*\) .*/\1/'`

                if [ "$ned" != "$oed" ] ; then 
                        write_partition -p $IMAGE/root$n.img.cram $INSTALL_DEVICE$n
                        make_active $INSTALL_DEVICE $n
                fi
        fi

        editions=`packcramfs -p -t -q ${INSTALL_DEVICE}${PACKED_PARTITION}`
        # now the cramfs partitions
        for i in $PACKED `cat $IMAGE/images | sort -u`
        do
                n=`echo $i | tr / .`
                m=$i
                if [ $i = main ] ; then m=/ ; fi
                oed=`echo $editions x | sed -n "s,.* $m \([0-9]*\) .*$,\1,p"`
                ned=`packcramfs -C -I -q $IMAGE/$n.img.cram | sed 's/edition \([0-9]*\) .*/\1/'`
                if [ "$oed" != "$ned" ] ; then
                        packcramfs -s -P --force ${INSTALL_DEVICE}${PACKED_PARTITION} $m $IMAGE/$n.img.cram
                        packcramfs -A  ${INSTALL_DEVICE}${PACKED_PARTITION} $m
                fi
        done

        sync; sync; sync
        echo "done -- wait until flash activity light is off"
}

function ml_make_image() {
        [ "$EDITION" != "" ]  || export EDITION=`date +%s`

        KERNEL=$BUILD/linux/arch/i386/boot/bzImage
        mkdir -p $IMAGE
        rm -f $IMAGE/.done

        # make copy of root
        [ -d $ROOT.work ] && rm -rf $ROOT.work
        mv $ROOT $ROOT.work
        fix=

        # switch to make sure we only use the working version of root
        ORIG_ROOT=$ROOT
        ROOT=$ROOT.work
        export ROOT

        # test ELF files on root (add "-s" to also strip in the future)
        find $ROOT -type f -print0 | xargs -0 elvenkind -w midori | sed "s@:.*$ROOT@: @"

        # split the image into root partition, main partition and all requested images
        [ -d $PARTS ] && rm -rf $PARTS 2> /dev/null
        mkdir -p $PARTS

        # get config image if needed
        if [ "$CONFIG_CREATE_SCRIPT" != "" ] ; then
                cd $TARGET
                . $CONFIG_CREATE_SCRIPT
                cd $BUILD
        fi

        # start with subdirectories (they are easier to find
        # if we do it now). They need to be reverse sorted to
        # avoid conflicts.
        images=
        for i in `sort -u -r < $IMAGE/images`
        do
                n=`echo $i | tr / .`
                if [ -d $ROOT/$i ] ; then
                        mv $ROOT/$i $PARTS/$n
                        mkdir $ROOT/$i
                        fix="rmdir $ROOT/$i ; mv $PARTS/$n $ROOT/$i ; $fix"
                        images="$i $images" # order is important, we need the mount order here!
                fi
        done


        # the main parts of the packed partition
        mkdir $PARTS/main
        [ -f $ROOT/.main_edition ] && mv $ROOT/.main_edition $PARTS/main/.edition
        for i in $PACKED
        do
                n=`echo $i | tr / .`
                mv $ROOT/$i $PARTS/$n
                mkdir $PARTS/main/$n
                ln -s /cramfs/$n $ROOT/$i
                fix="rm $ROOT/$i ; mv $PARTS/$n $ROOT/$i ; $fix"
                images="$i $images"
        done

        mv $ROOT $PARTS/root
        fix="mv $PARTS/root $ROOT ; $fix"

        # build the image

        let root_size=`du -sb $PARTS/root | awk '{print $1}'`

        # build padded kernel image
        calcmd5sum root
        md5sum $KERNEL >> $IMAGE/root.md5sum.n
        if [ -f $IMAGE/root.md5sum -a -f $IMAGE/root1.img.cram ] ; then
                if cmp $IMAGE/root.md5sum $IMAGE/root.md5sum.n ; then
                        rm $IMAGE/root.md5sum.n
                else
                        rm $IMAGE/root.md5sum
                fi
        fi

        if [ ! -f $IMAGE/root.md5sum ] ; then
                dd if=/dev/zero of=$IMAGE/bzImage.padded bs=436c count=1
                cat $KERNEL >> $IMAGE/bzImage.padded
                e=$EDITION
                if [ -f $PARTS/root/.edition ] ; then
                        e=`cat $PARTS/root/.edition`;
                        rm $PARTS/root/.edition;
                fi
                mkcramfs -E -p -e $e -i $IMAGE/bzImage.padded -z $PARTS/root $IMAGE/roott.img.cram
                cp $TARGET/cramfsboot.bin $IMAGE/root1.img.cram
                tail +513c  $IMAGE/roott.img.cram >>  $IMAGE/root1.img.cram
                cramfsck $IMAGE/root1.img.cram
                cp $IMAGE/root1.img.cram  $IMAGE/root2.img.cram 
                set_boot $IMAGE/root1.img.cram 1
                set_boot $IMAGE/root2.img.cram 2
                rm $IMAGE/roott.img.cram
                mv $IMAGE/root.md5sum.n $IMAGE/root.md5sum
        fi

        force=0
        if [ -f $IMAGE/main.img.packed ] ; then
                mv $IMAGE/main.img.packed $IMAGE/main.img.packed.tmp
        else
                rm -f $IMAGE/main.img.packed.tmp
                packcramfs -c -l 10 -i $PACKED_IMAGES -b 1024 $IMAGE/main.img.packed.tmp 1024
                force=1
        fi

        for i in main $images
        do
                n=`echo $i | tr / .`
                e=$EDITION
                if [ -f $PARTS/$n/.edition ] ; then
                        e=`cat $PARTS/$n/.edition`;
                        rm $PARTS/$n/.edition;
                fi
                [ "$force" = 0 ] || rm -f $IMAGE/$n.md5sum
                calcmd5sum $n
                if [ -f $IMAGE/$n.md5sum -a -f $IMAGE/$n.img.cram ] ; then
                        if cmp $IMAGE/$n.md5sum $IMAGE/$n.md5sum.n ; then
                                rm $IMAGE/$n.md5sum.n
                                continue
                        else
                                rm $IMAGE/$n.md5sum
                        fi
                fi
                mkcramfs -E -e $e -z $PARTS/$n $IMAGE/$n.img.cram
                cramfsck $IMAGE/$n.img.cram
                m=$i
                if [ $m = "main" ] ; then m=/ ; fi
                packcramfs -s -f --append $IMAGE/main.img.packed.tmp $m $IMAGE/$n.img.cram 
                packcramfs -A $IMAGE/main.img.packed.tmp $m
                mv $IMAGE/$n.md5sum.n $IMAGE/$n.md5sum
        done

        # make packcramfs file as small as possible (compact, then truncate)
        packcramfs -z $IMAGE/main.img.packed.tmp
        packcramfs -C --fast --write --resize $IMAGE/main.img.packed.tmp
        mv $IMAGE/main.img.packed.tmp $IMAGE/main.img.packed
        chmod a+r $IMAGE/main.img.packed	# packcramfs hard-coded to create it 0600

        echo $fix | sh -e
        if [ -d $ORIG_ROOT ] ; then
                #???? someone created a root directory? we better abort
                rm -rf $ROOT
        else
                mv $ROOT $ORIG_ROOT
        fi

        touch $IMAGE/.done
}

