#!/bin/bash
#
#  JaM Builder
#
#      (C) 2004 Yasushi kinneko Date   kinneko@po.incl.ne.jp
#
#  "JaM Builder" is the script which reconstructs and
#  remaster ISO image for 'MEPIS' Linux Distribution.
#
#  This script based on "YAK Builder 0.02".
#  (C) 2003 Yutaro Ebihara  ebihara@si-linux.com
#  http://www.si-linux.co.jp/pub/yakbuilder/
#
# The JaM Builder is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# the JaM Builder 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.
#
#   Jan 02 2004  v.0.01 1st  relaease
#   Jan 16 2004  v.0.02 update : add isocopy
#   Jan 27 2004  v.0.03 update : add mkswap, jamver
#   Feb 07 2004  v.0.04 update : add change_ja_fdimg
#   Apr 21 2004  v.0.05 update : add make_works
#   Apr 26 2004  v.0.06 update : some bug fixed
#   Apr 28 2004  v.0.07 update : bug fixed and colorize messages
#   May 06 2004  v.0.08 bugfix and samefilesweeper(fix same files)
#
APNAME="JaMbuilder"
VERSION=0.08
DIST_NAME="JaMEPIS"

SOURCE_DIR=./source
MASTER_DIR=./master
WORK_DIR=./parts
CDROM=/mnt/auto/cdrom
ISO=mepis-2003.10.01.cd1.iso

# Echo color change list
RESET="]R"       # Reset fb color mode
CRE="
[K"       # ANSI COLORS Erase to end of line
CLEAR="c"        # Clear and reset Screen
NORMAL="[0;39m"  # Normal color
RED="[1;31m"     # RED: Failure or error message
GREEN="[1;32m"   # GREEN: Success message
YELLOW="[1;33m"  # YELLOW: Descriptions
BLUE="[1;34m"    # BLUE: System mesages
MAGENTA="[1;35m" # MAGENTA: Found devices or drivers
CYAN="[1;36m"    # CYAN: Questions
WHITE="[1;37m"   # BOLD WHITE: Hint

# -------------------------------- functions ------------------------------------

function make_works () {
    check_root
    if  ! [ -d $SOURCE_DIR ]; then
	mkdir -p $SOURCE_DIR
    fi
    if  ! [ -d $MASTER_DIR ]; then
	mkdir -p $MASTER_DIR
    fi
    if  ! [ -d $WORK_DIR ]; then
	mkdir -p $WORK_DIR
    fi
}

function isocopy () {
    check_root
    make_works

    # mount iso image
    if ! [ -d /mnt/iso ]; then
        mkdir -p /mnt/iso
    fi

    mount -o loop $ISO /mnt/iso

    echo "${BLUE} copying from $ISO to $MASTER_DIR directory.....${NORMAL}"
    rsync -au --progress /mnt/iso/* $MASTER_DIR

    # get cloop.o from boot.img
    if ! [ -d /mnt/image ]; then
        mkdir -p /mnt/image
    fi
    mount -o loop /mnt/iso/boot/boot.img /mnt/image
    cp /mnt/image/initrd.gz ./
    umount /mnt/image
    gzip -d ./initrd.gz
    mount -o loop ./initrd /mnt/image
    cp /mnt/image/modules/cloop.o ./
    umount /mnt/image
    rm ./initrd
    rm -r /mnt/image

    if ! [ -e /dev/cloop ]; then
        mknod /dev/cloop b 240 0
    fi
    if ! [ -d /mnt/cloop ]; then
        mkdir /mnt/cloop
    fi
    if ! [ -f $MASTER_DIR/linux/linux ]; then
        echo "${RED}[ERROR] cloop image nothing!${NORMAL}"
	exit 0
    else 
        insmod ./cloop.o file=$MASTER_DIR/linux/linux
#            if ! [ $? -eq 0 ]; then
#                echo "  [WARNING] $? check your system."
#                exit 0
#            else
                mount -o ro /dev/cloop /mnt/cloop
#            fi
    fi

    echo ""
    echo "${BLUE} copying from MEPIS cloop image to $SOURCE_DIR directory.....${NORMAL}"
    rsync -avu --delete /mnt/cloop/* $SOURCE_DIR
    umount /mnt/cloop
    rmmod cloop
    rm $MASTER_DIR/linux/linux
    rm /dev/cloop
    rm -r /mnt/cloop
    rm ./cloop.o
    umount /mnt/iso
    rm -r /mnt/iso

    samefilesweeper

    echo ""
    echo "${GREEN}okay finish. type 'jambuilder edit' and add or delete packages.${NORMAL}"
}

function edit (){
    check_root
    echo "${GREEN}Add or delete packages.${NORMAL}"
    echo "${GREEN}type 'exit' when you want to exit.${NORMAL}"
    mount -t proc proc $SOURCE_DIR/proc
    mv $SOURCE_DIR/etc/resolv.conf $SOURCE_DIR/etc/resolv.conf-jam
    cp /etc/resolv.conf $SOURCE_DIR/etc/resolv.conf

    if [ $DISPLAY ]; then
	$XTERM -e chroot $SOURCE_DIR
    else
        chroot $SOURCE_DIR
    fi
    rm $SOURCE_DIR/etc/resolv.conf
    mv $SOURCE_DIR/etc/resolv.conf-jam $SOURCE_DIR/etc/resolv.conf
    umount $SOURCE_DIR/proc
    echo "${GREEN}okay finish. next type 'jambuilder mkcloop'${NORMAL}"
}

function mkcloop () {
    check_root
    chkswap
    if ! [ -d $SOURCE_DIR ]; then
	echo "${RED} ERROR! there is no $SOURCE_DIR dir${NORMAL}"
	exit 1
    fi
    if ! [ -d $MASTER_DIR ]; then
	echo "${RED} ERROR! there is no $MASTER_DIR dir${NORMAL}"
	exit 1
    fi

    #
    # set log files to zero byte
    #
    echo "${BLUE} clean up log files${NORMAL}"
    cleanup_logs

    change_ja_fdimg

    echo $DIST_NAME`date +%Y%m%d%H%M%S` > ./jamver
    JAMVER=`cat ./jamver`
    echo "$JAMVER made by $APNAME$VERSION" `date +%Y%m%d%H%M%S`> $SOURCE_DIR/etc/jamver

    # build JaMEPIS cloop image
    mkisofs -R -l -V "$JAMVER" -hide-rr-moved \
           $SOURCE_DIR | create_compressed_fs - 65536 > $MASTER_DIR/linux/linux

    chkswap

    echo "${GREEN}Finish!${NORMAL}"
    echo "${GREEN}Next, type 'jambuilser mkiso'.${NORMAL}"
}

function cleanup_logs () {
    check_root
    find $SOURCE_DIR/var/log  -exec cp /dev/null {} \;
}

function mkiso () {
    check_root
    chkswap
    if ! [ -d $MASTER_DIR ]; then
	echo "${RED}ERROR! there is no $MASTER_DIR dir${NORMAL}"
	exit 1
    fi

    JAMVER=`cat ./jamver`
    echo "$JAMVER made by $APNAME$VERSION" > $MASTER_DIR/jamver

    mkisofs -r -J -l -V "$JAMVER LiveCD" -hide-rr-moved \
           -b boot/boot.img \
           -c boot/boot.cat \
           -o $JAMVER-cd.iso \
           $MASTER_DIR/

    chkswap # clean swap temp

    echo "${GREEN}Finish!${NORMAL}"
    echo "${GREEN}Next, burn CD-ROM for Utilities(like 'K3b') and type 'jambuilder cleanall'.${NORMAL}"
}

function cleanall () {
    echo "${GREEN} [cleanall] clean all temporaly file and directory.${NORMAL}"
    echo "${BLUE} now cleaning. wait a moment.${NORMAL}"
    check_root
    if [ -d $SOURCE_DIR ]; then
        rm -rf $SOURCE_DIR
    fi
    if [ -d $MASTER_DIR ]; then
        rm -rf $MASTER_DIR
    fi
    if [ -d $WORK_DIR  ]; then
        rm -rf $WORK_DIR
    fi
    if [ -f ./jamver ]; then
        rm ./jamver
    fi
    echo "${BLUE} OK. cleaning complete.${NORMAL}"
}

function check_root () {
    if [ $UID != 0 ]; then
	echo "${RED}ERROR! you have to run as a root, or use sudo and try again.${NORMAL}"
	exit 1
    fi
}

function chkswap () {
    echo "${GREEN} [chkswap] checking swap area size.${NORMAL}"
    # SWAP OFF and DEL swap.temp
    if [ -f ./swap.temp ]; then
        echo "${YELLOW} temporaly swap is already using. swapoff and remove it.${NORMAL}"
        swapoff ./swap.temp
        rm ./swap.temp
    else
        if [ -f ./enoughswap ]; then
            rm ./enoughswap
	else
            # free swap space need about 1GB. check and get space.
            # NEEDSWAP=524288 #512MB
            NEEDSWAP=786432 #768MB
            # NEEDSWAP=1048576 #1GB
            FREESWAP=$(free| grep -i Swap| awk '{print $4}')
            echo "${BLUE} Now, free swap size is $FREESWAP bytes.${NORMAL}"
            if [ $FREESWAP -ge $NEEDSWAP ] ; then
               echo "${BLUE} OK! Swap size is able to bulding.${NORMAL}"
               touch ./enoughswap
            else
               echo "${YELLOW} Swap size is NOT able to bulding.${NORMAL}"
               # check disk free space
               # if
               #    echo "${RED}Sorry, no disk space.${NORMAL}"
               # else
               #    echo "${BLUE}enable disk space.${NORMAL}"
                   echo "${BLUE} Now, getting temporaly swap space. Wait a moment.${NORMAL}"
                   dd if=/dev/zero of=./swap.temp bs=1024 count=$NEEDSWAP ;\
                   /sbin/mkswap ./swap.temp $NEEDSWAP ;\
                   /bin/sync; /sbin/swapon ./swap.temp
               # fi
            fi
        fi
    fi
}

function change_ja_fdimg () {
    FUNCTION_NAME="change_ja_fdimg"
    echo "${GREEN} [change_ja_fdimg]: making japanese keyboard boot image.${NORMAL}"
        #echo "${GREEN}[function]: $FUNCTION_NAME..............${NORMAL}"

    if [ -f ./jp106.kbd ]; then
        cp ./jp106.kbd $WORK_DIR
    fi

    #
    # delete work files
    #
    function nekobaba () {

        #
        # delete jp106.kbd
        #
        if [ -f $WORK_DIR/jp106.kbd ]; then
            if [ "$JP106KBDSTAT" = "MADE" ]; then
                #echo "${BLUE} delteing $WORK_DIR/jp106.kbd.${NORMAL}"
                rm $WORK_DIR/jp106.kbd
                if ! [ $? -eq 0 ]; then
                    echo " ${YELLOW}[WARNING] missing delete $WORK_DIR/jp106.kbd. error code is $?${NORMAL}"
                    #exit 0
                fi
            #else
                #echo " ${BLUE}file $WORK_DIR/jp106.kbd exist defaultly. stop delete.${NORMAL}"
            fi
        fi

        #
        # delete work dir /mnt/image
        #
        if [ -d /mnt/image ]; then
            if [ "$MNTIMANGESTAT" = "MADE" ]; then
                #echo " ${GREEN}delteing mount point /mnt/image.${NORMAL}"
                rm -r /mnt/image
                if ! [ $? -eq 0 ]; then
                    echo " ${YELLOW}[WARNING] missing delete /mnt/image. error code is $?${NORMAL}."
                    #exit 0
                fi
            #else
                #echo " ${BLUE}mount point /mnt/image exist defaultly. stop delete.${NORMAL}"
            fi
        fi
    }


    #
    # check boot.img existence
    #
    if ! [ -f $MASTER_DIR/boot/boot.img ]; then
        echo " ${RED}Sorry, no boot.img file. Please check it.${NORMAL}"
        exit 0
    else
        echo " ${BLUE}OK. boot.image exist.${NORMAL}"
    fi

    #
    # check jp106.kbd existence
    #
    JP106KBDSTAT="" # ./jp106.kbd exitsing check flag
    if ! [ -f $WORK_DIR/jp106.kbd ]; then
        echo " ${YELLOW}jp106.kbd is not found at work dir. now getting remote site.${NORMAL}"
        wget http://prdownloads.sourceforge.jp/jambuilder/8054/jp106.kbd -O $WORK_DIR/jp106.kbd > /dev/null 2>&1
        if ! [ -f $WORK_DIR/jp106.kbd ]; then
            echo "  ${RED}May be missing download jp106.kbd.${NORMAL}"
            nekobaba
            exit 0
        else
            JP106KBDSTAT="MADE"
            echo "  ${BLUE}jp106.kbd downloaded.${NORMAL}"
        fi
    else
        echo " ${BLUE}jp106.kbd found at work dir.${NORMAL}"
            JP106KBDSTAT="DEFAULT"
    fi

    #
    # make work dir /mnt/image
    #
    MNTIMANGESTAT="" # /mnt/image exitsing check flag
    if ! [ -d /mnt/image ]; then
        echo " ${BLUE}making mount point /mnt/image.${NORMAL}"
        mkdir -p /mnt/image
            if ! [ $? -eq 0 ]; then
                echo "  ${RED}missing mkdir /mnt/image. error code is $?.${NORMAL}"
                exit 0
            fi
        MNTIMANGESTAT="MADE"
    else
        #echo " ${YELLOW}/mnt/image already exist.${NORMAL}"
        MNTIMANGESTAT="DEFAULT"
    fi
    #echo " ${BLUE}/mnt/image status $MNTIMANGESTAT.${NORMAL}"

    #
    # make jp106 boot.img
    #
    if mount | grep /mnt/image > /dev/null 2>&1 ; then
        echo " ${RED}/mnt/image already mounted. check your system.${NORMAL}"
        nekobaba
        exit 0
    fi
    MOUNTFLAG="" # mount check flag
    mount -o loop $MASTER_DIR/boot/boot.img /mnt/image
        if ! [ $? -eq 0 ]; then
            echo " ${RED}missing mount /mnt/image. error code is $?.${NORMAL}"
            nekobaba
            exit 0
        else
            echo " ${BLUE}mounted boot.img.${NORMAL}"
        fi
        MOUNTFLAG="SELF"
    if ! [ -f /mnt/image/jp106.kbd ] ; then
        echo " ${BLUE}copying jp106.kbd to boot.img.${NORMAL}"
        cp $WORK_DIR/jp106.kbd /mnt/image
            if ! [ $? -eq 0 ]; then
                echo " ${RED}missing copy jp106.kbd. error code is $?.${NORMAL}"
                nekobaba
                exit 0
            fi
    else
        echo " ${YELLOW}jp106.kbd already exists in boot.img.${NORMAL}"
    fi

    # add "KBDMAP jp106.kbd" to syslinux.cfg
    CFGEXISTENCE=""
    CFGEXISTENCE=`grep jp106.kbd /mnt/image/syslinux.cfg`
##########   why missing this check part?
#            if ! [ $? -eq 0 ]; then
#                echo " missing check syslinux.cfg. error code is $?."
#                echo " CFGEXTENCE = [$CFGEXISTENCE]"
#                nekobaba
#                exit 0
#            fi

    if [ "$CFGEXISTENCE" = "" ] ; then
        echo "KBDMAP jp106.kbd" >> /mnt/image/syslinux.cfg
            if ! [ $? -eq 0 ]; then
                echo " ${RED}missing add KBDMAP jp106.kbd to syslinux.cfg. error code is $?.${NORMAL}"
                nekobaba
                exit 0
            fi
        echo " ${GREEN}jp106.kbd added in syslinux.cfg.${NORMAL}"
    else
        echo " ${YELLOW}jp106.kbd already setting in syslinux.cfg.${NORMAL}"
    fi

    if [ "$MOUNTFLAG" = "SELF" ] ; then
        umount /mnt/image
            if ! [ $? -eq 0 ]; then
                echo " ${RED}missing umount /mnt/image. error code is $?.${NORMAL}"
                nekobaba
                exit 0
            fi
        echo " ${GREEN}umounted /mnt/image.${NORMAL}"
    #else
        #echo " ${YELLOW}/mnt/image is mounted defaultly.${NORMAL}"
    fi

    #
    # cleanup temp files
    #
    nekobaba
}


function samefilesweeper () {
    echo "${GREEN} [samefilesweeper] now replace same files.${NORMAL}"
    while read LINE
    do
        ln -f $LINE
        #echo "${GREEN} replace $LINE${NORMAL}"
    done < ./samefile.lst
    echo "${BLUE} finish replacement.${NORMAL}"
}


# ============================
#
# main routine start from here
#
# ============================

echo "${BLUE}"
echo "JaM Builder version $VERSION"
echo "(C) 2004  Yasushi kinneko Date  <kinneko@po.incl.ne.jp>"
echo "${NORMAL}"

case "$1" in
    isocopy)
        if ! [ -f $ISO ]; then
		echo "${RED} ERROR: cdrom image '$ISO' is not exit.${NORMAL}"
		echo "${RED} get and put the cdrom image and try again.${NORMAL}"
	else
		echo "${GREEN}[isocopy] copy from $ISO image${NORMAL}"
		isocopy
	fi
    ;;
    edit)
	echo "${GREEN}[edit] edit chroot directory${NORMAL}"
	edit
    ;;
    mkcloop)
	echo "${GREEN}[mkcloop] build cloop image to $MASTER_DIR/linux/linux${NORMAL}"
	mkcloop
    ;;
    mkiso)
	echo "${GREEN}[mkiso] build iso image${NORMAL}"
	mkiso
    ;;
    cleanall)
	echo "${GREEN}[clean] remove and cleanup $SOURCE_DIR , $MASTER_DIR directory${NORMAL}"
	echo -n "${GREEN}Sure? type 'yes' to cleanup ->${NORMAL}"
	read yesno
	if [ $yesno == 'yes' ]; then
	    cleanall
	fi
    ;;
    *)
        echo "  Usage: jambuilder {isocopy|edit|mkcloop|mkiso|cleanall}"
	echo ""
        echo "    isocopy: Copy files from $ISO to $SOURCE_DIR and $MASTER_DIR."
        echo "       edit: Chroot into the $DIST_NAME Userland, install and remove packages."
        echo "    mkcloop: Build cloop $DIST_NAME Userland image."
        echo "      mkiso: Build bootable iso image file."
        echo "   cleanall: Cleanup $SOURCE_DIR and $MASTER_DIR directory."
        echo ""
	exit 1
    ;;
esac

exit 0

