#!/bin/sh

#
# Load the configuration file
#
source jhalfs.conf


version="
jhalfs development \$Date$

Written by Jeremy Huntwork and Manuel Canales Esparcia.

This program is published under the \
Gnu General Public License, Version 2.
"

usage="\
Usage: $0 [OPTION]

Options:
  -h, --help                    print this help, then exit

  -V, --version                 print version number, then exit

  -d  --directory DIR           use DIR directory for building LFS; all files
                                jhalfs produces will be in the directory
                                DIR/jhalfs. Default is \"/mnt/lfs\".

  -P, --get-packages            download the packages and patches. This
                                assumes that the server declared in the 
                                jhalfs.conf file has the proper packages
                                and patches for the book version being
                                processed.

  -D, --download-client CLIENT  use CLIENT as the program for retrieving
                                packages (for use in conjunction with -P)

  -W, --working-copy DIR        use the local working copy placed in DIR
                                as the LFS book

  -L, --LFS-version VER         checkout VER version of the LFS book.
                                Supported versions at this time are:
                                
         dev* | trunk | SVN     aliases for Development LFS
         testing | 6.1.1        aliases for the testing 6.1.1 branch 

  -T, --testsuites              add support to run the optional testsuites

  --no-toolchain-test           don't run the toolchain testsuites. This
                                also disables the build of TCL, Expect
                                and DejaGNU

  --no-strip                    don't run the strip command on both the
                                temporary system and the final system

  --timezone TIMEZONE           set TIMEZONE as the local timezone. If not
                                specified, \"Europe/London\" will be used.

  --page_size PAGE              set PAGE as the default page size (letter
                                or A4). This setting is required to
                                build Groff. If not specified, \"letter\"
                                will be used.

  --fstab FILE                  use FILE as the /etc/fstab file for the
                                LFS system. If not specified, a default
                                /etc/fstab file with dummy values is
                                created.
  
  --no-vim-lang                 don't install the optional vim-lang package

  -C, --kernel-config FILE      use the kernel configuration file specified
                                in FILE to build the kernel. If the file is
				not found, or if not specified, the kernel
				build is skipped.

  -M, --run-make                run make on the generated Makefile

"

help="\
Try '$0 --help' for more information."

no_empty_builddir="\
echo \"\" >&2
echo \"        W A R N I N G\" >&2
echo \"\" >&2
echo \"Looks like the \$BUILDDIR directory contains subdirectories\" >&2
echo \"from a previous LFS build.\" >&2
echo \"\" >&2
echo \"Please format the partition mounted on \$BUILDDIR or set\" >&2
echo \"a diferent build directory before to run jhalfs.\" >&2
echo \"\" >&2
exit 1"

exit_missing_arg="\
echo \"Option '\$1' requires an argument\" >&2
echo \"\$help\" >&2
exit 1"

no_dl_client="\
echo \"Could not find a way to download the LFS sources.\" >&2
echo \"Attempting to continue.\" >&2"

HEADER="# This file is automatically generated by jhalfs
# DO NOT EDIT THIS FILE MANUALLY
#
# Generated on `date \"+%F %X %Z\"`"


###################################
###	    FUNCTIONS		###
###################################


#----------------------------#
get_book() {
#----------------------------#
  # Check for Subversion instead of just letting the script hit 'svn' and fail.
  test `type -p svn` || eval "echo \"This feature requires Subversion.\"
  exit 1"
  cd $JHALFSDIR

  if [ -z $WC ] ; then
    echo -n "Downloading the LFS Book, version $LFSVRS... "

    # Grab the LFS book fresh if it's missing, otherwise, update it from the
    # repo. If we've already extracted the commands, move on to getting the
    # sources.
    if [ -d lfs-$LFSVRS ] ; then
      cd lfs-$LFSVRS
      if svn up | grep -q At && test -d $JHALFSDIR/commands && \
      test -f $JHALFSDIR/packages && test -f $JHALFSDIR/patches ; then
        echo -ne "done\n"
        # Set the canonical book version
        cd $JHALFSDIR
        VERSION=`grep "ENTITY version " $BOOK/general.ent | sed 's@<!ENTITY version "@@;s@">@@'`
        get_sources
      else
        echo -ne "done\n"
        # Set the canonical book version
        cd $JHALFSDIR
        VERSION=`grep "ENTITY version " $BOOK/general.ent | sed 's@<!ENTITY version "@@;s@">@@'`
        extract_commands
      fi
    else
      if [ $LFSVRS = development ] ; then
        svn co $SVN/LFS/trunk/BOOK lfs-$LFSVRS >>$LOGDIR/$LOG 2>&1
      else
        svn co $SVN/LFS/branches/$LFSVRS/BOOK lfs-$LFSVRS >>$LOGDIR/$LOG 2>&1
      fi
      echo -ne "done\n"
      # Set the canonical book version
      cd $JHALFSDIR
      VERSION=`grep "ENTITY version " $BOOK/general.ent | sed 's@<!ENTITY version "@@;s@">@@'`
      extract_commands
    fi
  else
    echo -ne "Using $BOOK as book's sources ...\n"
    # Set the canonical book version
    cd $JHALFSDIR
    VERSION=`grep "ENTITY version " $BOOK/general.ent | sed 's@<!ENTITY version "@@;s@">@@'`
    extract_commands
  fi
}

#----------------------------#
extract_commands() {
#----------------------------#
  # Check for libxslt instead of just letting the script hit 'xsltproc' and fail.
  test `type -p xsltproc` || eval "echo \"This feature requires libxslt.\"
  exit 1"
  cd $JHALFSDIR

  # Start clean
  if [ -d commands ] ; then rm -rf commands ; fi && mkdir commands
  echo -n "Extracting commands... "

  # Dump the commands in shell script form from the LFS book.
  xsltproc --nonet --xinclude --stringparam testsuite $TEST \
    --stringparam toolchaintest $TOOLCHAINTEST --stringparam vim-lang $VIMLANG \
    -o ./commands/ $XSL $BOOK/index.xml >>$LOGDIR/$LOG 2>&1

  # Make the scripts executable.
  chmod -R +x $JHALFSDIR/commands

  # Grab the patches and package names.
  cd $JHALFSDIR
  for i in patches packages ; do rm -f $i ; done
  grep "\-version" $BOOK/general.ent | sed -e 's@<!ENTITY @@' -e 's@">@"@' \
  -e '/generic/d' >> packages
  echo `grep "glibc" packages | sed 's@glibc@&-linuxthreads@'` >> packages
  # Download the vim-lang package if it must be installed
  if [ "$VIMLANG" = "1" ] ; then
    echo `grep "vim" packages | sed 's@vim@&-lang@'` >> packages
  fi
  echo `grep "udev-config-file" $BOOK/general.ent | sed -e 's@<!ENTITY @@' -e 's@">@"@'` >> packages
  # Download the module-init-tools-testsuite package only 
  # if the test suite will be run.
  if [ "$TEST" = "1" ] ; then
    echo `grep "module" packages | sed 's@tools@&-testsuite@'` >> packages
  fi
  # If we are buildind the UTF-8 branch, the glibc-libidn package is required
  if grep -q "man-db-version" $BOOK/general.ent ; then
    echo `grep "glibc" packages | sed 's@glibc@glibc-libidn@'` >> packages
  fi
  grep "ENTITY" $BOOK/patches.ent | sed -e 's/.* "//' -e 's/">//' >> patches

  # Done. Moving on...
  echo -ne "done\n"
  get_sources
}

#----------------------------#
download() {
#----------------------------#
  cd $BUILDDIR/sources

  # Hackish fix for the bash-doc, glibc-{linuxthreads,libidn} and
  # module-init-tools-testsuite packages that doesn't conform to 
  # norms in the URL scheme.
  DIR=`echo $1 | sed 's@-doc@@;s@-linuxthreads@@;s@-libidn@@;s@-testsuite@@'`

  # Find the md5 sum for this package.
  if [ $2 != MD5SUMS ] ; then MD5=`grep "  $2" MD5SUMS` ; fi

  if [ ! -f $2 ] ; then
    case $DL in
      wget )
        wget $HTTP/$DIR/$2
        ;;
      curl )
        `curl -# $HTTP/$DIR/$2 -o $2`
        ;;
      * )
        echo "$DL not supported at this time."
        ;;
    esac
  elif ! echo "$MD5" | md5sum -c - >/dev/null 2>/dev/null ; then
    case $DL in
      wget )
        wget -c $HTTP/$DIR/$2
        ;;
      curl )
        `curl -# -C - $HTTP/$DIR/$2 -o $2`
        ;;
      * )
        echo "$DL not supported at this time."
        ;;
    esac
  fi
  if [ $2 != MD5SUMS ] && ! echo "$MD5" | md5sum -c - ; then
    exit 1
  fi
  if [ $2 != MD5SUMS ] ; then
    echo `grep "$MD5" MD5SUMS` >> MD5SUMS-$VERSION
  fi
}

#----------------------------#
get_sources() {
#----------------------------#

  # Test if the packages must be downloaded
  if [ "$HPKG" = "1" ] ; then

    # This variable is necessary to make sure the `cat $JHALFSDIR/packages`
    # separates each iteration by lines.  It is necessary to have the second
    # ' on the next line.
    IFS='
'

    if [ ! -d $BUILDDIR/sources ] ; then mkdir $BUILDDIR/sources ; fi
    cd $BUILDDIR/sources
    if [ -f MD5SUMS ] ; then rm MD5SUMS ; fi
    if [ -f MD5SUMS-$VERSION ] ; then rm MD5SUMS-$VERSION ; fi

    download "" MD5SUMS

    # Iterate through each package and grab it, along with any patches it needs.
    for i in `cat $JHALFSDIR/packages` ; do
      PKG=`echo $i | sed -e 's/-version.*//' -e 's/-file.*//'`
      # Needed for Groff patchlevel patch on UTF-8 branch
      GROFFLEVEL=`grep "groff-patchlevel" $JHALFSDIR/packages | sed -e 's/groff-patchlevel //' -e 's/"//g'`

      # There is some entities that aren't valid package entities.
      if [ "$PKG" = "expect-lib" -o "$PKG" = "linux-dl" -o "$PKG" = "groff-patchlevel" ] ; then continue ; fi

      VRS=`echo $i | sed -e 's/.* //' -e 's/"//g'`
      if [ "$PKG" = "tcl" ] ; then
        FILE="$PKG$VRS-src.tar.bz2"
      elif [ "$PKG" = "vim-lang" ] ; then
        PKG="vim"
        FILE="vim-$VRS-lang.tar.bz2"
      elif [ "$PKG" = "udev-config" ] ; then
        PKG="udev"
        FILE="$VRS"
      else
        FILE="$PKG-$VRS.tar.bz2"
      fi
      download $PKG $FILE
      for patch in `grep "$PKG-&$PKG" $JHALFSDIR/patches` ; do
        PATCH=`echo $patch | sed 's@&'$PKG'-version;@'$VRS'@'`
        download $PKG $PATCH
      done
      # Needed for Groff patchlevel patch on UTF-8 branch
      for patch in `grep "patchlevel" $JHALFSDIR/patches` ; do
        PATCH=`echo $patch | sed 's@&'$PKG'-version;-&'$PKG'-patchlevel;@'$VRS'-'$GROFFLEVEL'@'`
        download $PKG $PATCH
      done
    done
  fi
}

#-----------------------------------------------#
_IS_()  # Function to test build scripts names
#-----------------------------------------------#
{
  # Returns substr $2 or null str
  # Must use string testing
  case $1 in
    *$2*) echo "$2" ;;
       *) echo ""   ;;
  esac
}

#----------------------------#
chapter4_Makefiles() {
#----------------------------#
(
    cat << EOF
020-creatingtoolsdir:
	@\$(call echo_message, Building)
	@mkdir -v \$(LFS)/tools && \\
	rm -fv /tools && \\
	ln -sv \$(LFS)/tools / && \\
	touch \$@

021-addinguser:  020-creatingtoolsdir
	@\$(call echo_message, Building)
	@groupadd lfs && \\
	useradd -s /bin/bash -g lfs -m -k /dev/null lfs && \\
	chown lfs \$(LFS)/tools && \\
	chown lfs \$(LFS)/sources && \\
	touch \$@

022-settingenvironment:  021-addinguser
	@\$(call echo_message, Building)
	@echo "set +h" > /home/lfs/.bashrc && \\
	echo "umask 022" >> /home/lfs/.bashrc && \\
	echo "LFS=/mnt/lfs" >> /home/lfs/.bashrc && \\
	echo "LC_ALL=POSIX" >> /home/lfs/.bashrc && \\
	echo "PATH=/tools/bin:/bin:/usr/bin" >> /home/lfs/.bashrc && \\
	echo "export LFS LC_ALL PATH" >> /home/lfs/.bashrc && \\
	echo "source $JHALFSDIR/envars" >> /home/lfs/.bashrc && \\
	chown lfs:lfs /home/lfs/.bashrc && \\
	touch envars && \\
	touch \$@
EOF
) >> $MKFILE.tmp
}

#----------------------------#
chapter5_Makefiles() {
#----------------------------#
  for file in chapter05/* ; do
    # Keep the script file name
    i=`basename $file`

    # If no testsuites will be run, then TCL, Expect and DejaGNU isn't needed
    if [ "$TOOLCHAINTEST" = "0" ]; then
      if [[ `_IS_ $i tcl` ]] || [[ `_IS_ $i expect` ]] || [[ `_IS_ $i dejagnu` ]] ; then
        continue
      fi
    fi

    # Test if the stripping phase must be skipped
    if [ "$STRIP" = "0" ] && [[ `_IS_ $i stripping` ]] ; then
      continue
    fi

    # First append each name of the script files to a list (this will become
    # the names of the targets in the Makefile
    chapter5="$chapter5 $i"

    # Grab the name of the target (minus the -pass1 or -pass2 in the case of gcc
    # and binutils in chapter 5)
    name=`echo $i | sed -e 's@[0-9]\{3\}-@@' -e 's@-pass[0-9]\{1\}@@'`

    # Set the dependency for the first target.
    if [ -z $PREV ] ; then PREV=022-settingenvironment ; fi

    # Drop in the name of the target on a new line, and the previous target
    # as a dependency. Also call the echo_message function.
(
    cat << EOF

$i:  $PREV
	@\$(call echo_message, Building)
EOF
) >> $MKFILE.tmp

    # Find the version of the command files, if it corresponds with the building of
    # a specific package
    vrs=`grep "^$name-version" $JHALFSDIR/packages | sed -e 's/.* //' -e 's/"//g'`

    # If $vrs isn't empty, we've got a package...
    if [ "$vrs" != "" ] ; then
      if [ "$name" = "tcl" ] ; then
        FILE="$name$vrs-src.tar"
      else
        FILE="$name-$vrs.tar"
      fi

      # Insert instructions for unpacking the package and to set
      # the PKGDIR variable.
(
    cat << EOF
	@\$(call unpack,$FILE)
	@ROOT=\`head -n1 /tmp/unpacked | sed 's@^./@@;s@/.*@@'\` && \\
	chown -R lfs \$(LFS)\$(SRC)/\$\$ROOT && \\
	echo "PKGDIR=\$(LFS)\$(SRC)/\$\$ROOT" > envars && \\
	echo "export PKGDIR" >> envars && \\
EOF
) >> $MKFILE.tmp

    fi

    # Dump the path to the Binutils or TCL sources directory.
    if [[ `_IS_ $i binutils` ]] || [[ `_IS_ $i tcl` ]] ; then
(
    cat << EOF
	echo "\$(LFS)\$(SRC)/\$\$ROOT" > sources-dir
EOF
) >> $MKFILE.tmp

    # For the Adjusting phase we must to cd to the binutils-build directory.
    elif [[ `_IS_ $i adjusting` ]] ; then
(
    cat << EOF
	@echo "PKGDIR=\$(LFS)\$(SRC)/binutils-build" > envars && \\
	echo "export PKGDIR" >> envars
EOF
) >> $MKFILE.tmp

    # For the Expect build we need to set the TCLPATH envar.
    elif [[ `_IS_ $i expect` ]] ; then
(
    cat << EOF
	echo "TCLPATH=\`cat sources-dir\`" >> envars && \\
	echo "export TCLPATH" >> envars
EOF
) >> $MKFILE.tmp

    # Everything else, add a true statment so we don't confuse make
    else
(
    cat << EOF
	true
EOF
) >> $MKFILE.tmp
    fi

    # Insert date and disk usage at the top of the log file, the script run
    # and date and disk usage again at the bottom of the log file.
(
    cat << EOF
	@echo -e "\n\`date\`\n\nKB: \`du -sk --exclude={0,1}??-* \$(LFS)\`\n" >logs/$i && \\
	su - lfs -c "source /home/lfs/.bashrc && $JHALFSDIR/commands/$file" >>logs/$i 2>&1 && \\
	echo -e "\n\`date\`\n\nKB: \`du -sk --exclude={0,1}??-* \$(LFS)\`\n" >>logs/$i
EOF
) >> $MKFILE.tmp

    # Remove the build directory(ies) except if the package build fails
    # (to can review config.cache, config.log, and like.)
    # For Binutils and TCL the sources must be retained some time.
    if [ "$vrs" != "" ] ; then
      if [[ ! `_IS_ $i binutils` ]] && [[ ! `_IS_ $i tcl` ]] ; then
(
    cat << EOF
	@ROOT=\`head -n1 /tmp/unpacked | sed 's@^./@@;s@/.*@@'\` && \\
	rm -r \$(LFS)\$(SRC)/\$\$ROOT && \\
	if [ -e \$(LFS)\$(SRC)/$name-build ]; then \\
		rm -r \$(LFS)\$(SRC)/$name-build; \\
	fi;
EOF
) >> $MKFILE.tmp
      fi
    fi

    # Remove the Binutils pass 1 sources after a successful Adjusting phase.
    if [[ `_IS_ $i adjusting` ]] ; then
(
    cat << EOF
	@rm -r \`cat sources-dir\` && \\
	rm -r \$(LFS)\$(SRC)/binutils-build && \\
	rm sources-dir
EOF
) >> $MKFILE.tmp
    fi

    # Remove the TCL sources after a successful Expect build.
    if [[ `_IS_ $i expect` ]] ; then
(
    cat << EOF
	@rm -r \`cat sources-dir\` && \\
	rm sources-dir
EOF
) >> $MKFILE.tmp
    fi

    # Include a touch of the target name so make can check
    # if it's already been made.
(
    cat << EOF
	@touch \$@
EOF
) >> $MKFILE.tmp

    # Keep the script file name for Makefile dependencies.
    PREV=$i
  done  # end for file in chapter05/*
}

#----------------------------#
chapter6_Makefiles() {
#----------------------------#
  for file in chapter06/* ; do
    # Keep the script file name
    i=`basename $file`

    # We'll run the chroot commands differently than the others, so skip them in the
    # dependencies and target creation.
    if [[ `_IS_ $i chroot` ]] ; then
       continue
    fi

    # Test if the stripping phase must be skipped
    if [ "$STRIP" = "0" ] && [[ `_IS_ $i stripping` ]] ; then
      continue
    fi

    # First append each name of the script files to a list (this will become
    # the names of the targets in the Makefile
    chapter6="$chapter6 $i"

    # Grab the name of the target
    name=`echo $i | sed -e 's@[0-9]\{3\}-@@'`

    # Drop in the name of the target on a new line, and the previous target
    # as a dependency. Also call the echo_message function.
(
    cat << EOF

$i:  $PREV
	@\$(call echo_message, Building)
EOF
) >> $MKFILE.tmp

    # Find the version of the command files, if it corresponds with the building of
    # a specific package
    vrs=`grep "^$name-version" $JHALFSDIR/packages | sed -e 's/.* //' -e 's/"//g'`

    # If $vrs isn't empty, we've got a package...
    # Insert instructions for unpacking the package and changing directories
    if [ "$vrs" != "" ] ; then
      FILE="$name-$vrs.tar.*"
(
    cat  << EOF
	@\$(call unpack2,$FILE)
	@ROOT=\`head -n1 /tmp/unpacked | sed 's@^./@@;s@/.*@@'\` && \\
	echo "PKGDIR=\$(SRC)/\$\$ROOT" > envars && \\
	echo "export PKGDIR" >> envars
EOF
) >> $MKFILE.tmp
    fi

    # For the Re-Adjusting phase we must to cd to the binutils-build directory.
    if [[ `_IS_ $i readjusting` ]] ; then
(
    cat << EOF
	@echo "PKGDIR=\$(SRC)/binutils-build" > envars && \\
	echo "export PKGDIR" >> envars
EOF
) >> $MKFILE.tmp

    # For Glibc we need to set TIMEZONE envar.
    elif [[ `_IS_ $i glibc` ]] ; then
(
    cat << EOF
	@echo "TIMEZONE=\$(TIMEZONE)" >> envars && \\
	echo "export TIMEZONE" >> envars
EOF
) >> $MKFILE.tmp

    # For Groff we need to set PAGE envar.
    elif [[ `_IS_ $i groff` ]] ; then
(
    cat << EOF
	@echo "PAGE=\$(PAGE)" >> envars && \\
	echo "export PAGE" >> envars
EOF
) >> $MKFILE.tmp
    fi

    # In the mount of kernel filesystems we need to set LFS
    # and not to use chroot.
    if [[ `_IS_ $i kernfs` ]] ; then
(
    cat << EOF
	@echo -e "\n\`date\`\n\nKB: \`du -sk --exclude={0,1}??-* \$(LFS)\`\n" >logs/$i && \\
	export LFS=\$(LFS) && commands/$file >>logs/$i 2>&1 && \\
	echo -e "\n\`date\`\n\nKB: \`du -sk --exclude={0,1}??-* \$(LFS)\`\n" >>logs/$i
EOF
) >> $MKFILE.tmp

    # The rest of Chapter06
    else
(
    cat << EOF
	@echo -e "\n\`date\`\n\nKB: \`du -skx --exclude={0,1}??-* \$(LFS)\`\n" >logs/$i && \\
	\$(CHROOT1) 'cd /jhalfs && source envars && /jhalfs/commands/$file >>/jhalfs/logs/$i 2>&1' && \\
	echo -e "\n\`date\`\n\nKB: \`du -skx --exclude={0,1}??-* \$(LFS)\`\n" >>logs/$i
EOF
) >> $MKFILE.tmp
    fi

    # Remove the build directory(ies) except if the package build fails.
    if [ "$vrs" != "" ] ; then
(
    cat << EOF
	@ROOT=\`head -n1 /tmp/unpacked | sed 's@^./@@;s@/.*@@'\` && \\
	rm -r \$(LFS)\$(SRC)/\$\$ROOT && \\
	if [ -e \$(LFS)\$(SRC)/$name-build ]; then \\
		rm -r \$(LFS)\$(SRC)/$name-build; \\
	fi;
EOF
) >> $MKFILE.tmp
    fi

    # Remove the Binutils pass 2 sources after a successful Re-Adjusting phase.
    if [[ `_IS_ $i readjusting` ]] ; then
(
    cat << EOF
	@rm -r \`cat sources-dir\` && \\
	rm -r \$(LFS)\$(SRC)/binutils-build && \\
	rm sources-dir
EOF
) >> $MKFILE.tmp
    fi

    # Include a touch of the target name so make can check
    # if it's already been made.
(
    cat << EOF
	@touch \$@
EOF
) >> $MKFILE.tmp

    # Keep the script file name for Makefile dependencies.
    PREV=$i
  done # end for file in chapter06/*
}

#----------------------------#
chapter789_Makefiles() {
#----------------------------#
  for file in chapter0{7,8,9}/* ; do
    # Keep the script file name
    i=`basename $file`

    # Grub must be configured manually.
    # The filesystems can't be unmounted via Makefile and the user
    # should to enter to the chroot environment to create the root
    # password, edit several files and setup Grub,
    if [[ `_IS_ $i grub` ]] || [[ `_IS_ $i reboot` ]] ; then
       continue
    fi

    # If no .config file is supplied, the kernel build is skipped
    if [ -z $CONFIG ] && [[ `_IS_ $i kernel` ]] ; then
      continue
    fi

    # First append each name of the script files to a list (this will become
    # the names of the targets in the Makefile
    chapter789="$chapter789 $i"

    # Drop in the name of the target on a new line, and the previous target
    # as a dependency. Also call the echo_message function.
(
    cat << EOF

$i:  $PREV
	@\$(call echo_message, Building)
EOF
) >> $MKFILE.tmp

    # Find the the bootscripts and kernel package names
    if [[ `_IS_ $i bootscripts` ]] || [[ `_IS_ $i kernel` ]] ; then
      if [[ `_IS_ $i bootscripts` ]] ; then
        vrs=`grep "^lfs-bootscripts-version" $JHALFSDIR/packages | sed -e 's/.* //' -e 's/"//g'`
        FILE="lfs-bootscripts-$vrs.tar.*"
      elif [[ `_IS_ $i kernel` ]] ; then
        vrs=`grep "^linux-version" $JHALFSDIR/packages | sed -e 's/.* //' -e 's/"//g'`
        FILE="linux-$vrs.tar.*"
      fi
(
    cat  << EOF
	@\$(call unpack2,$FILE)
	@ROOT=\`head -n1 /tmp/unpacked | sed 's@^./@@;s@/.*@@'\` && \\
	echo "PKGDIR=\$(SRC)/\$\$ROOT" > envars && \\
	echo "export PKGDIR" >> envars
EOF
) >> $MKFILE.tmp
    fi

    # Put in place the kernel .config file
    if [[ `_IS_ $i kernel` ]] ; then
(
    cat << EOF
	@cp $CONFIG \$(LFS)/sources/kernel-config
EOF
) >> $MKFILE.tmp
    fi

    # Check if we have a real /etc/fstab file
    if [[ `_IS_ $i fstab` ]] && [[ -n "$FSTAB" ]] ; then
(
    cat << EOF
	@echo -e "\n\`date\`\n\nKB: \`du -skx --exclude={0,1}??-* \$(LFS)\`\n" >logs/$i && \\
	cp -v $FSTAB \$(LFS)/etc/fstab >>logs/$i 2>&1 && \\
	echo -e "\n\`date\`\n\nKB: \`du -skx --exclude={0,1}??-* \$(LFS)\`\n" >>logs/$i
EOF
) >> $MKFILE.tmp
    else
    # Initialize the log an run the script
(
    cat << EOF
	@echo -e "\n\`date\`\n\nKB: \`du -skx --exclude={0,1}??-* \$(LFS)\`\n" >logs/$i && \\
	\$(CHROOT2) 'cd /jhalfs && source envars && /jhalfs/commands/$file >>/jhalfs/logs/$i 2>&1' && \\
	echo -e "\n\`date\`\n\nKB: \`du -skx --exclude={0,1}??-* \$(LFS)\`\n" >>logs/$i
EOF
) >> $MKFILE.tmp
    fi

    # Remove the build directory except if the package build fails.
    if [[ `_IS_ $i bootscripts` ]] || [[ `_IS_ $i kernel` ]] ; then
(
    cat << EOF
	@ROOT=\`head -n1 /tmp/unpacked | sed 's@^./@@;s@/.*@@'\` && \\
	rm -r \$(LFS)\$(SRC)/\$\$ROOT
EOF
) >> $MKFILE.tmp
    fi

    # Include a touch of the target name so make can check
    # if it's already been made.
(
    cat << EOF
	@touch \$@
EOF
) >> $MKFILE.tmp

    # Keep the script file name for Makefile dependencies.
    PREV=$i
  done  # for file in chapter0{7,8,9}/*
} 


#----------------------------#
build_Makefile() {
#----------------------------#
  echo -n "Creating Makefile... "
  cd $JHALFSDIR/commands

  # Start with a clean Makefile.tmp file
  >$MKFILE.tmp

  chapter4_Makefiles
  chapter5_Makefiles
  chapter6_Makefiles  
  chapter789_Makefiles  


  # Add a header, some variables and include the function file
  # to the top of the real Makefile.
(
    cat << EOF
$HEADER

SRC= /sources
LFS= $BUILDDIR
PAGE= $PAGE
TIMEZONE= $TIMEZONE

include functions

EOF
) > $MKFILE


  # Add chroot commands
  i=1
  for file in chapter06/*chroot* ; do
    chroot=`cat $file | sed -e '/#!\/bin\/sh/d' -e 's@ \\\@ @g' | tr -d '\n' | sed \
      -e 's/  */ /g' -e 's|\\$|&&|g' -e 's|exit||g' -e 's|$| -c|' \
      -e 's|"$$LFS"|$(LFS)|' -e 's|set -e||'`
    echo -e "CHROOT$i= $chroot\n" >> $MKFILE
    i=`expr $i + 1`
  done

  # Drop in the main target 'all:' and the chapter targets with each sub-target
  # as a dependency.
(
    cat << EOF
all:  chapter4 chapter5 chapter6 chapter789
	@\$(call echo_finished,$VERSION)

chapter4:  020-creatingtoolsdir 021-addinguser 022-settingenvironment

chapter5:  chapter4 $chapter5

chapter6:  chapter5 $chapter6

chapter789:  chapter6 $chapter789

clean-all:  clean
	rm -rf ./*

clean:  clean-chapter789 clean-chapter6 clean-chapter5 clean-chapter4

clean-chapter4:
	-userdel lfs
	rm -rf /home/lfs
	rm -rf \$(LFS)/tools
	rm -f /tools
	rm -f envars
	rm -f 02* logs/02*.log

clean-chapter5:
	rm -rf \$(LFS)/tools/*
	rm -f $chapter5
	cd logs && rm -f $chapter5 && cd ..
  
clean-chapter6:
	-umount \$(LFS)/sys
	-umount \$(LFS)/proc
	-umount \$(LFS)/dev/shm
	-umount \$(LFS)/dev/pts
	-umount \$(LFS)/dev
	rm -rf \$(LFS)/{bin,boot,dev,etc,home,lib,media,mnt,opt,proc,root,sbin,srv,sys,tmp,usr,var}
	rm -f $chapter6
	cd logs && rm -f $chapter6 && cd ..

clean-chapter789: 
	rm -f $chapter789
	cd logs && rm -f $chapter789 && cd ..


EOF
) >> $MKFILE

  # Bring over the items from the Makefile.tmp
  cat $MKFILE.tmp >> $MKFILE
  rm $MKFILE.tmp
  echo -ne "done\n"
}

#----------------------------#
run_make() {
#----------------------------#
  # Test if make must be run.
  if [ "$RUNMAKE" = "1" ] ; then
    # Test to make sure we're running the build as root
    if [ "$UID" != "0" ] ; then
      echo "You must be logged in as root to successfully build LFS."
      exit 1
    fi
    # Build the system
    if [ -e $MKFILE ] ; then
      echo -ne "Building the LFS system...\n"
      cd $JHALFSDIR && make
      echo -ne "done\n"
    fi
  fi
}



###################################
###		MAIN		###
###################################

# Evaluate any command line switches

while test $# -gt 0 ; do
  case $1 in
    --version | -V )
      echo "$version"
      exit 0
      ;;

    --help | -h )
      echo "$usage"
      exit 0
      ;;

    --LFS-version | -L )
      test $# = 1 && eval "$exit_missing_arg"
      shift
      case $1 in
        dev* | SVN | trunk )
          LFSVRS=development
          ;;
        testing | 6.1.1 )
          LFSVRS=6.1.1
          ;;
	
	alpha*)
	  LFSVRS=alphabetical
	  ;;
        * )
          echo "$1 is an unsupported version at this time."
          exit 1
          ;;
      esac
      ;;

    --directory | -d )
      test $# = 1 && eval "$exit_missing_arg"
      shift
      BUILDDIR=$1
      ;;

    --download-client | -D )
      test $# = 1 && eval "$exit_missing_arg"
      shift
      DL=$1
      ;;

    --working-copy | -W )
      test $# = 1 && eval "$exit_missing_arg"
      shift
      if [ -f $1/patches.ent ] ; then
      WC=1
      BOOK=$1
      else
        echo -e "\nLook like $1 isn't a supported working copy."
        echo -e "Verify your selection and the command line.\n"
        exit 1
      fi
      ;;

    --testsuites | -T )		TEST=1 ;;

    --get-packages | -P )	HPKG=1 ;;

    --run-make | -M )		RUNMAKE=1 ;;

    --no-toolchain-test )	TOOLCHAINTEST=0 ;;

    --no-strip )	STRIP=0 ;;

    --no-vim-lang )	VIMLANG=0 ;;
    
    --page_size )
      test $# = 1 && eval "$exit_missing_arg"
      shift
      case $1 in
        letter | A4 )
          PAGE=$1
          ;;
        * )
          echo "$1 isn't a supported page size."
          exit 1
          ;;
      esac
      ;;


    --timezone )
      test $# = 1 && eval "$exit_missing_arg"
      shift
      if [ -f /usr/share/zoneinfo/$1 ] ; then
        TIMEZONE=$1
      else
        echo -e "\nLook like $1 isn't a valid timezone description."
        echo -e "Verify your selection and the command line.\n"
        exit 1
      fi
      ;;

    --fstab )
      test $# = 1 && eval "$exit_missing_arg"
      shift
      if [ -f $1 ] ; then
        FSTAB=$1
      else
        echo -e "\nFile $1 not found. Verify your command line.\n"
        exit 1
      fi
      ;;

    --kernel-config | -C )
      test $# = 1 && eval "$exit_missing_arg"
      shift
      if [ -f $1 ] ; then
        CONFIG=$1
      else
        echo -e "\nFile $1 not found. Verify your command line.\n"
        exit 1
      fi
      ;;

    * )
      echo "$usage"
      exit 1
      ;;
  esac
  shift
done

# If $BUILDDIR have subdirectories like tools/ or bin/, stop the run
# and notify the user about that. This also prevents setting "-d /"
# by mistake.

if [ -d $BUILDDIR/tools -o -d $BUILDDIR/bin ] ; then
  eval "$no_empty_builddir"
fi

# Find the download client to use, if not already specified.

if [ -z $DL ] ; then
  if [ `type -p wget` ] ; then
    DL=wget
  elif [ `type -p curl` ] ; then
    DL=curl
  else
    eval "$no_dl_client"
  fi
fi

[[ ! -d $JHALFSDIR ]]        && mkdir -pv $JHALFSDIR
[[ "$PWD" != "$JHALFSDIR" ]] && cp -v $FILES $JHALFSDIR/ && \
  sed -e 's/FAKEDIR/'$BOOK'/' $XSL > $JHALFSDIR/dump-lfs-scripts.xsl && \
  export XSL=$JHALFSDIR/dump-lfs-scripts.xsl
[[ ! -d $LOGDIR ]]           && mkdir -v $LOGDIR
>$LOGDIR/$LOG

get_book
build_Makefile
run_make