#!/bin/bash
#If you uncomment the set -x following, bash will show every command before it 
#is executed.
#set -x
#
#Make sure Makefile has BKSCRIPTVER updated when this changes
BKSCRIPTVER='0.83'
# Buildkernel, version 0.83
# 	This script will automatically open up the linux kernel source 
# .tar.gz, patch it, configure it, build it, and install it for you.  
# It automatically cleans out code from other architectures.  
#	To get going quickly, read the QUICKSTART file that is part of 
# this package.  For detailed information on how to customize the build 
# process, read buildkernel.doc .  Both of these files should be part of
# the buildkernel package.  They were probably installed to 
# /usr/doc/buildkernel-{version}/ .  If they are missing or you would like 
# to make sure you have the latest version, please go to 
# http://www.pobox.com/~wstearns/buildkernel/  .
#
# To change the operation of buildkernel, do not change the variables below.  
# Instead, read buildernel.doc to see how.  (For the impatient, create 
# ~/.bkrc and put any variables you wish to change in it.)  Keep in mind 
# that this script has intelligent defaults for all of the following and 
# displays them for you before starting.
#
#Copyleft:
#    Buildkernel is used to create a new linux kernel from the raw source
#    and patches.
#    Copyright (C) 1997 William Stearns <wstearns@pobox.com>
#
#    This program 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.
#
#    This program 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.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#    The author can also be reached at:
#        William Stearns
#email:  wstearns@pobox.com              (preferred)
#web:    http://www.pobox.com/~wstearns
#snail:  544 Winchester Place
#        Colchester VT, 05446
#
# Do not change any variables below this line; internal variables
#
#We are going to send all output to /tmp/BKlog and rename it at the end if 
#necessary.

#-----------------------------------------------------------------------
#Internal Functions
#-----------------------------------------------------------------------
bkheader () {
    #This way allows status messages before BKVERBOSE is set.
    if [ ! "${BKVERBOSE}" = "NO" ]; then
        echo  2>&1 | tee -a /tmp/BKlog
        echo  2>&1 | tee -a /tmp/BKlog
        echo  2>&1 | tee -a /tmp/BKlog
        echo -----------------------------------------------------------------------  2>&1 | tee -a /tmp/BKlog
    fi
    echo -- $* --  2>&1 | tee -a /tmp/BKlog
    if [ ! "${BKVERBOSE}" = "NO" ]; then
        echo -----------------------------------------------------------------------  2>&1 | tee -a /tmp/BKlog
    fi
}
bkstatus () {
    #This way allows status messages before BKVERBOSE is set.
    if [ ! "${BKVERBOSE}" = "NO" ]; then
        echo ---------- $*
    fi
    echo ---------- $* >>/tmp/BKlog 2>&1
}
bkwarn () {
    echo XXXXXXXXXX $*  2>&1 | tee -a /tmp/BKlog
}

bksplitversion () {
#'bksplitversion 2.0.32' returns VERSION=2, PATCHLEVEL=0, SUBLEVEL=32 in
#the shell environment
    unset VERSION PATCHLEVEL SUBLEVEL
    BKLEGALVER=YES

    VERSION=`echo ${1} | gawk --field-separator '.' '{ print $1 }'`
    PATCHLEVEL=`echo ${1} | gawk --field-separator '.' '{ print $2 }'`
    SUBLEVEL=`echo ${1} | gawk --field-separator '.' '{ print $3 }'`

#I am not going to deal with 00, 001, 000, etc.
#And yes, this will break when linux 2.3.1000 comes out ;-)
    case ${VERSION} in
    [0-9]|[0-9][0-9]|[0-9][0-9][0-9])   : ;;
    *)                                  BKLEGALVER="NO" ;;
    esac
    case ${PATCHLEVEL} in
    [0-9]|[0-9][0-9]|[0-9][0-9][0-9])   : ;;
    *)                                  BKLEGALVER="NO" ;;
    esac
    case ${SUBLEVEL} in
    [0-9]|[0-9][0-9]|[0-9][0-9][0-9])   : ;;
    *)                                  BKLEGALVER="NO" ;;
    esac
}


#-----------------------------------------------------------------------
#Initialize internal variables
#-----------------------------------------------------------------------
BKPATCHESAPPLIED=NO
BKFREESPACE=0
BKSHOWHELP=NO
BKSHOWVER=NO
BKORIGPARAMS="$0 $*"

#-----------------------------------------------------------------------
#Create log file and header
#-----------------------------------------------------------------------
#NOTE: If the last build failed, I think we want to keep the partial log.  
#This allows the user to see _all_ the steps that led up to a successful build.
#On the other hand, if /tmp/BKlog is a symlink, someone may be trying to 
#get this script to dump garbage in the symlink target.
if [ -L /tmp/BKlog ]; then
    #This rm uses a complete path, so we don't need to check pwd.
    rm -f /tmp/BKlog
    touch /tmp/BKlog
fi

echo ----------------------------------------------------------------------- 2>&1 | tee -a /tmp/BKlog
echo Buildkernel Version ${BKSCRIPTVER}  2>&1 | tee -a /tmp/BKlog
echo Run on `date` on `hostname`  2>&1 | tee -a /tmp/BKlog
echo Command line is:  2>&1 | tee -a /tmp/BKlog
echo ${BKORIGPARAMS}  2>&1 | tee -a /tmp/BKlog
echo ----------------------------------------------------------------------- 2>&1 | tee -a /tmp/BKlog
echo 2>&1 | tee -a /tmp/BKlog


#-----------------------------------------------------------------------
#Load user configuration and initialize variables
#-----------------------------------------------------------------------


#-----------------------------
bkstatus Load.1: Loading system preferences.
#-----------------------------
#FIXME check for illegal values
if [ -f /etc/bkrc ]; then
    . /etc/bkrc
    bkstatus /etc/bkrc preferences loaded
else
    bkwarn no /etc/bkrc, problem?
fi

#-----------------------------
bkstatus Load.2: Loading user preferences.
#-----------------------------
#FIXME check for illegal values
if [ -f ~/.bkrc ]; then
    . ~/.bkrc
    bkstatus ~/.bkrc preferences loaded
else
    bkstatus no ~/.bkrc, problem? Ignore this warning if this is the first
    bkstatus time running this script.
    bkstatus Creating ~/.bkrc
    if [ -f /etc/bkrc ] ; then
        bkstatus creating ~/.bkrc from /etc/bkrc
        #The following sed adds a '#' at the beginning of any uncommented line.
        cat /etc/bkrc | sed -e 's/^\([^#]\)/#\1/' > ~/.bkrc
    else
        bkwarn There is no /etc/bkrc to copy to ~/.bkrc.  Proceeding anyway.
        bkwarn You can get a complete copy of this script package from 
        bkwarn http://www.pobox.com/~wstearns/
    fi
    chmod 644 ~/.bkrc
fi


#-----------------------------
bkstatus Load.3: Load command line parameters
#-----------------------------

until [ "$*" = "" ]; do
    # Following statement is "if there is an equals sign in ${1} then"
    if [ "`echo ${1} | sed -e s/[^=]//g | cut -b 1`" = "=" ]; then
        BKVALUE=`echo ${1} | sed -e s/.*=//`
        #I do not want to fix case for all parameters; filenames are case sensitive.
        #If one is silly enough to want to log to the file "yes", well...
        case `echo ${BKVALUE} | tr a-z A-Z` in
          YES)		BKVALUE=YES				;;
          NO)		BKVALUE=NO				;;
          NEWESTBETA)	BKVALUE=NEWESTBETA			;;
          NEWESTSTABLE)	BKVALUE=NEWESTSTABLE			;;
          NEWESTPCMCIA)	BKVALUE=NEWESTPCMCIA			;;
          CONFIG)	BKVALUE=config				;;
          MENUCONFIG)	BKVALUE=menuconfig			;;
          XCONFIG)	BKVALUE=xconfig				;;
        esac
    else
        BKVALUE=''    
    fi

    case `echo ${1} | tr a-z A-Z | sed -e s/=.*//` in
    --HELP|--BKHELP)
        BKSHOWHELP=YES
        shift							;;
    --VERSION|--BKVERSION)
        BKSHOWVER=YES
        shift							;;
    --AUTOGET|--BKAUTOGET)	
        BKAUTOGET=${BKVALUE:-YES}
        shift							;;
    --BUILDTYPE|--BKBUILDTYPE)
        if [ "${BKVALUE}" != "" ]; then
            BKBUILDTYPE=${BKVALUE}
        fi
        shift							;;
    --COPYTOFLOPPY|--BKCOPYTOFLOPPY)
        BKCOPYTOFLOPPY=${BKVALUE:-YES}
        shift							;;
    --DEBUG|--BKDEBUG)
        BKDEBUG=${BKVALUE:-YES}
        shift							;;
    --INTERACTIVE|--BKINTERACTIVE)
        BKINTERACTIVE=${BKVALUE:-YES}
        shift							;;
    --KERNELTOBUILD|--BKKERNELTOBUILD)
        if [ "${BKVALUE}" != "" ]; then
            BKKERNELTOBUILD=${BKVALUE}
        fi
        shift							;;
    --LOAD|--BKLOAD)
        if [ "${BKVALUE}" != "" ]; then
            BKLOAD=${BKVALUE}
        fi
        shift							;;
    --MAKECLEANBEFORE|--BKMAKECLEANBEFORE)
        BKMAKECLEANBEFORE=${BKVALUE:-YES}
        shift							;;
    --MAKECLEANAFTER|--BKMAKECLEANAFTER)
        BKMAKECLEANAFTER=${BKVALUE:-YES}
        shift							;;
    --MAKETYPE|--BKMAKETYPE)
        if [ "${BKVALUE}" != "" ]; then
            BKMAKETYPE=${BKVALUE}
        fi
        shift							;;
    --NUMBUILDS|--BKNUMBUILDS)
        if [ "${BKVALUE}" != "" ]; then
            BKNUMBUILDS=${BKVALUE}
        fi
        shift							;;
    --OPENFRESH|--BKOPENFRESH)
        BKOPENFRESH=${BKVALUE:-YES}
        #I could probably set MAKECLEANBEFORE=YES if 
        #OPENFRESH=YES, but it makes no difference.  
        #Build files will get deleted anyways.
        shift							;;
    --PCMCIATOBUILD|--BKPCMCIATOBUILD)
        if [ "${BKVALUE}" != "" ]; then
            BKPCMCIATOBUILD=${BKVALUE:}
        fi
        shift							;;
    --ROOTDEVICE|--BKROOTDEVICE)
        if [ "${BKVALUE}" != "" ]; then
            BKROOTDEVICE=${BKVALUE}
        fi
        shift							;;
    --SOURCEDIR|--BKSOURCEDIR)
        if [ "${BKVALUE}" != "" ]; then
            BKSOURCEDIR=${BKVALUE}
        fi
        shift							;;
    --VERBOSE|--BKVERBOSE)
        BKVERBOSE=${BKVALUE:-YES}
        shift							;;
    --VIDMODE|--BKVIDMODE)
        if [ "${BKVALUE}" != "" ]; then
            BKVIDMODE=${BKVALUE}
        fi
        shift							;;
    --EDITOR|--BKEDITOR)
        if [ "${BKVALUE}" != "" ]; then
            EDITOR=${BKVALUE}
        fi
        shift							;;
    --HOSTTYPE|--BKHOSTTYPE)
        if [ "${BKVALUE}" != "" ]; then
            HOSTTYPE=${BKVALUE}
        fi
        shift							;;
    --HOSTNAME|--BKHOSTNAME)
        if [ "${BKVALUE}" != "" ]; then
            HOSTNAME=${BKVALUE}
        fi
        shift							;;
    --USER|--BKUSER)
        if [ "${BKVALUE}" != "" ]; then
            USER=${BKVALUE}
        fi
        shift							;;
    NEWESTBETA|--NEWESTBETA)
        BKKERNELTOBUILD=NEWESTBETA
        shift							;;
    NEWESTSTABLE|--NEWESTSTABLE|NEWESTVERSION|--NEWESTVERSION)
        BKKERNELTOBUILD=NEWESTSTABLE
        shift							;;
    NEWESTPCMCIA|--NEWESTPCMCIA)
        BKPCMCIATOBUILD=NEWESTPCMCIA
        shift							;;
    [0-9].[0-9].[0-9]|[0-9].[0-9].[1-9][0-9]|[0-9].[0-9].[1-9][0-9][0-9]|[0-9].[1-9][0-9].[0-9]|[0-9].[1-9][0-9].[1-9][0-9]|[0-9].[1-9][0-9].[1-9][0-9][0-9])
        if [ "${BKKERNELTOBUILD}" = "" ]; then
            BKKERNELTOBUILD=`echo ${1} | sed -e s/=.*//`
        else
            BKPCMCIATOBUILD=`echo ${1} | sed -e s/=.*//`
        fi
        shift							;;
    *)
        bkwarn ${1} is not recognized as a valid command line parameter
        shift							;;
    esac
done
unset BKVALUE


#-----------------------------
bkstatus Load.4: Load version specific parameters
bkstatus Not currently implemented...
#-----------------------------
#FIXME


#-----------------------------
bkstatus Load.5: Load variables from last build of this version
bkstatus Not currently implemented...
#-----------------------------
#FIXME
#/usr/src/configs/.bkrc.version.onetime


#-----------------------------
bkstatus Load.6: Sanity checks on variables.
#-----------------------------

BKMAKETYPE=`echo ${BKMAKETYPE} | tr A-Z a-z`
case ${BKMAKETYPE} in
config|menuconfig|xconfig)
    bkstatus ${BKMAKETYPE} is a legal choice for maketype
    ;;
*)
    #Remember we only get here if BKMAKETYPE is not correctly set.  Any 
    #previous legal user choice would override this.
    if [ "`set | grep '^DISPLAY=' | wc -l | sed -e s/\ //g`" = "0" ]; then
	bkstatus Not in X-windows.
        if [ "`ls -al /usr/lib/libncurses* | wc -l | sed -e s/\ //g`" = "0" ]; then
            bkstatus Ncurses libraries not installed, config chosen for kernel configuration
            BKMAKETYPE=config
        else
            bkstatus Ncurses libraries installed, menuconfig chosen for kernel configuration
            BKMAKETYPE=menuconfig
        fi
    else
        bkstatus In X-windows, xconfig chosen for kernel configuration
        BKMAKETYPE=xconfig
    fi
    ;;
esac

# If not set, gnu make allows an infinite number of builds.
# By the way, if you have a 16 CPU machine, we need to talk... :-)
case ${BKNUMBUILDS} in
[1-9]|1[0-7])
    bkstatus BKNUMBUILDS is in the legal range of 1 to 17
    ;;
*)
    BKNUMBUILDS=$[`cat /proc/cpuinfo | grep ^processor | wc -l` + 1]
    bkwarn BKNUMBUILDS out of the range of 1 to 17, reset to ${BKNUMBUILDS}
    bkwarn which is the number of CPUs in your system plus 1.
    ;;
esac



#Following are defaults assigned to variables ONLY IF none of the previous
#steps have assigned values to these.
BKAUTOGET=`echo ${BKAUTOGET:-YES} | tr a-z A-Z`
BKBUILDTYPE=${BKBUILDTYPE:-zImage}
BKCOPYTOFLOPPY=`echo ${BKCOPYTOFLOPPY:-NO} | tr a-z A-Z`
BKDEBUG=`echo ${BKDEBUG:-NO} | tr a-z A-Z`
BKINTERACTIVE=`echo ${BKINTERACTIVE:-YES} | tr a-z A-Z`
BKKERNELTOBUILD=`echo ${BKKERNELTOBUILD:-NEWESTSTABLE} | tr a-z A-Z`
BKLOAD=${BKLOAD:-'nice -n 10'}
BKLOGFILE=${BKLOGFILE:-'/usr/src/linux/bklog'}
BKMAKECLEANBEFORE=`echo ${BKMAKECLEANBEFORE:-NO} | tr a-z A-Z`
BKMAKECLEANAFTER=`echo ${BKMAKECLEANAFTER:-NO} | tr a-z A-Z`
BKOPENFRESH=`echo ${BKOPENFRESH:-YES} | tr a-z A-Z`
BKPCMCIATOBUILD=`echo ${BKPCMCIATOBUILD:-NO} | tr a-z A-Z`
BKROOTDEVICE=${BKROOTDEVICE:-`cat /etc/mtab | grep ' / ' | cut -f 1 -d ' '`}
BKSOURCEDIR=${BKSOURCEDIR:-/usr/src/source/kernel/}
BKVERBOSE=`echo ${BKVERBOSE:-YES} | tr a-z A-Z`
BKVIDMODE=${BKVIDMODE:-'-2'}
HOSTNAME=${HOSTNAME:-localhost}
HOSTTYPE=${HOSTTYPE:-`uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc64/`}
USER=${USER:-root}
BKBUILDCOUNT=${BKBUILDCOUNT:-0}


if [ "${BKINTERACTIVE}" = "YES" ]; then
    for BKTRYEDITOR in `type -path pico` \
                       `type -path mcedit` \
                       `type -path vi` \
                       `type -path jove` \
                       `type -path nedit` \
                       `type -path emacs`; do
        if [ "${EDITOR}" = "" ]; then
            EDITOR=${BKTRYEDITOR}
            bkstatus Editor default of ${EDITOR} taken.
        fi
    done
    unset BKTRYEDITOR
    if [ "${EDITOR}" = "" ]; then
        bkwarn No editor was specified by the EDITOR= variable and 
        bkwarn this script was unable to find pico, vi, jove, or emacs
        bkwarn on your system.  Please set EDITOR=the_name_of_an_editor
        bkwarn in ~/.bkrc and re-run ${BKORIGPARAMS}
        exit
    fi #no suitable editor found
fi #INTERACTIVE


#-----------------------------
bkstatus Load.7: Display current settings
#-----------------------------
if [ "${BKVERBOSE}" = "YES" ]; then
    bkstatus -----------------------------
    set | grep -E '^BK|^EDITOR=|^HOSTNAME=|^HOSTTYPE=|^USER='  2>&1 | tee -a /tmp/BKlog
    bkstatus  -----------------------------
    bkstatus Pausing a few seconds so you can double check run-time settings.
    sleep 10		#Give user a few seconds to see what they are in for.
    bkstatus OK, off we go!
fi
if [ "${BKINTERACTIVE}" = "NO" ]; then
#FIXME remove when it works
    bkwarn You have chosen BKINTERACTIVE=NO.  This script is not currently 
    bkwarn able to work around a requirement of the linux kernel that one 
    bkwarn of the config choices be run.  We will have to run a standard 
    bkwarn config for the moment.
fi

#-----------------------------------------------------------------------
#Handle Help or Version requests
#-----------------------------------------------------------------------
if [ "${BKSHOWHELP}" = "YES" ]; then
    cat <<EOTEXT  2>&1 | tee -a /tmp/BKlog
Syntax: ${0} kernel-version [pcmcia-cs-version]

NOTE: if you do not use a system with pcmcia sockets, generally
just laptops, you can ignore every reference to pcmcia.

Example: ${0} 2.1.58 2.9.11
	Would build kernel 2.1.58 and pcmcia-cs 2.9.11

Example: ${0} 2.0.31
	Would build just kernel 2.0.31.

Example: ${0} NEWESTSTABLE NEWESTPCMCIA
	Instead of using specific kernel or pcmcia versions, you may 
	simply ask for the latest versions.  The script will figure 
	out what the latest versions are, download them if they are 
	not already here, and continue as if you had specified the 
	versions.  NEWESTSTABLE or NEWESTBETA can be used instead of
	an actual kernel version, and NEWESTPCMCIA can be used 
	instead of a pcmcia-cs version.  You can mix NEWESTsomething 
	and a real version on the command line.
	For this to work, you need an Internet connection from the 
	start of the script until one or both files are downloaded.
	You obviously cannot have both NEWESTBETA and NEWESTSTABLE
	at the same time.

NOTE: NEWESTPCMCIA and pcmcia-cs autodownload are not yet 
implemented... Sorry.  For the moment you will need to download
them yourself and specify the appropriate version.

Keep in mind that this script has intelligent defaults for all of the 
following and displays them for you before starting.

Command line parameters (defaults listed first, '|' separates examples):
--BKAUTOGET=YES|NO	#Can script go out and get missing source files?
--BKBUILDTYPE=zImage|zdisk|bzImage|bzdisk
--BKCOPYTOFLOPPY=NO|YES
--BKDEBUG=NO|YES
--BKINTERACTIVE=YES|NO	#'NO' means script should not ask user for anything
--BKKERNELTOBUILD=NEWESTSTABLE|NEWESTBETA|2.0.32|2.1.66|2.1.42...
--BKLOAD='nice -n 10'|''|'nice -n -4'
--BKLOGFILE='/usr/src/linux/bklog'|'~/bklog'
--BKMAKECLEANBEFORE=NO|YES
--BKMAKECLEANAFTER=NO|YES
--BKMAKETYPE=menuconfig|xconfig|config
--BKNUMBUILDS=2|1|3|4|5|...|17
--BKOPENFRESH=YES|NO
--BKPCMCIATOBUILD=NO|2.9.12|2.8.23|NEWESTPCMCIA
--BKROOTDEVICE=''|/dev/hda1|/dev/hda3|/dev/sda2|/dev/sdb1...
--BKSOURCEDIR=/usr/src/source/kernel/|/tmp
--BKVERBOSE=YES|NO
--BKVIDMODE='-2'|'-3'|'-1'|'0'|'1'|'2'...
--HOSTNAME=mymachine.mydomain.org|...
--HOSTTYPE=i386|alpha|m68k|mips|ppc|sparc|sparc64
--USER=root|wstearns|nobody...
--EDITOR='pico -w '|pico|mcedit|vi|jove|nedit|emacs...
--HELP			#Show this help
--VERSION		#Show version and copyleft information

If this scrolled off the screen too quickly, try
buildkernel --HELP | more<Enter>

EOTEXT
    exit
fi #BKSHOWHELP=YES
unset BKSHOWHELP

if [ "${BKSHOWVER}" = "YES" ]; then
    cat <<EOTEXT  2>&1 | tee -a /tmp/BKlog
Buildkernel, version ${BKSCRIPTVER}.
    Buildkernel is used to create a new linux kernel from the raw source
and patches. 
    Copyright (C) 1997 William Stearns <wstearns@pobox.com>
    This program 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. 
    This program 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.  See the GNU General Public License
for more details. 
    You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
    The author can also be reached at:
        William Stearns
email:  wstearns@pobox.com              (preferred)
web:    http://www.pobox.com/~wstearns
snail:  544 Winchester Place, Colchester VT, 05446
EOTEXT
    exit
fi #BKSHOWVER=YES
unset BKSHOWVER



#-----------------------------------------------------------------------
#Handle difficult running environment
#-----------------------------------------------------------------------
if [ $UID != 0 ]; then
#FIXME check for BKBUILDUSER
    bkwarn Hmmm... you do not seem to be user root.  It may
    bkwarn be the case that you _can_ compile a kernel on 
    bkwarn this system, but I make some assumptions about 
    bkwarn commands that are available to you that may not be 
    bkwarn true if you are not root.  If you meant to run this 
    bkwarn as root, press Ctrl-C now and run it as root.  If 
    bkwarn you meant to be running this while not root, the 
    bkwarn script will restart in 30 seconds.
    sleep 30
fi


if [ `ps -ax | grep [b]uildkernel | grep -v grep | wc -l | \
 sed -e s/\ //g` -le 2 ]; then
# For some wierd shell reason, probably tied to backquotes, just running 
# the above command under a single invocation produces _2_ entries in ps.  
# Grrr...
    bkstatus No other buildkernel running on the system, good.
else
    bkwarn There is another task running on the system with
    bkwarn buildkernel somewhere in its name.  ps -ax reports `ps -ax | grep [b]uildkernel | grep -v grep | wc -l | sed -e s/\ //g`
    bkwarn tasks with buildkernel in their name.  This number 
    bkwarn should be a 2.  This script was 
    bkwarn not designed to allow more than one copy running
    bkwarn at a time.  If you still wish to run this, please
    bkwarn wait until the other is finished or kill the other
    bkwarn program.  The following may help you determine 
    bkwarn what else is running...
    ps -ax | grep [b]uildkernel | grep -v grep  2>&1 | tee -a /tmp/BKlog
    exit
fi




cd /usr/src
if [ "${BKKERNELTOBUILD}" = "NEWESTSTABLE" ] || \
   [ "${BKKERNELTOBUILD}" = "NEWESTBETA" ]; then
    #-----------------------------------------------------------------------
    bkheader Translate NEWESTSTABLE or NEWESTBETA to a real version
    #-----------------------------------------------------------------------
    if [ "${BKKERNELTOBUILD}" = "NEWESTBETA" ]; then
        BKKERNELTYPE=beta
    else
        BKKERNELTYPE=stable
    fi
    bkstatus Figuring out what the newest ${BKKERNELTYPE} kernel is...
    #This rm uses a complete path, so we don't need to check pwd.
    rm -f /tmp/BKfingerkernel  2>&1 | tee -a /tmp/BKlog
    finger @linux.kernel.org >/tmp/BKfingerkernel  2>&1 | tee -a /tmp/BKlog
    bkstatus Here is what Linus reports as the latest ${BKKERNELTYPE} kernel
    cat /tmp/BKfingerkernel | grep -i ${BKKERNELTYPE}  2>&1 | tee -a /tmp/BKlog
    bkstatus

    bksplitversion `cat /tmp/BKfingerkernel                                 | \
     grep -i ${BKKERNELTYPE}                                                | \
     gawk --field-separator ':' '{ print $2 }'                              | \
     sed -e s/\ //g`

    bkstatus Version is ${VERSION}
    bkstatus Patchlevel is ${PATCHLEVEL}
    bkstatus Sublevel is ${SUBLEVEL}
    bkstatus The current series of the ${BKKERNELTYPE} kernel is ${VERSION}.${PATCHLEVEL}.${SUBLEVEL}
    BKKERNELTOBUILD=${VERSION}.${PATCHLEVEL}.${SUBLEVEL}
    BKAUTOGET=YES
fi




#-----------------------------------------------------------------------
bkheader Create necessary directories and links.
#-----------------------------------------------------------------------
cd /usr
for BKMAKEDIR in /usr/src/configs ${BKSOURCEDIR} /usr/include ; do
    if [ ! -d ${BKMAKEDIR} ]; then
        mkdir --parents ${BKMAKEDIR}  2>&1 | tee -a /tmp/BKlog
    fi
    if [ ! -d ${BKMAKEDIR} ]; then 
#FIXME more robust checking
        bkwarn Hmmm... I do not seem to be able to create directory
        bkwarn ${BKMAKEDIR} but need to to be able to to continue.
        bkwarn Could you check on this and rerun 
        bkwarn ${BKORIGPARAMS}  ? Thanks.
        exit
    fi
done
unset BKMAKEDIR


#Skip over kernel build
#if [ ! "${BKDEBUG}" = "YES" ]; then



#     Each of the following files should be symbolic links.  The first time 
#this is run, it is possible that we have something else, but we only need
#to deal with that once.  I am not going to deal with 
#making multi level backups of structures that should be symlinks anyways.

cd /usr
#Make sure each entry in the following is a complete path
for BKCHECKLINK in /usr/include/asm /usr/include/linux /usr/include/scsi \
                   /usr/src/linux ; do
    if [ -L ${BKCHECKLINK} ]; then
        bkstatus Removing symbolic link ${BKCHECKLINK}
        #This rm uses complete paths, so we don't need to check pwd.
        rm -f ${BKCHECKLINK}  2>&1 | tee -a /tmp/BKlog
    elif [ -e ${BKCHECKLINK} ]; then
        if [ -f ${BKCHECKLINK} ] || [ -d ${BKCHECKLINK} ]; then
            bkwarn renaming file or directory ${BKCHECKLINK} 
            bkwarn to ${BKCHECKLINK}.old
            #This rm uses a complete path, so we don't need to check pwd.
            rm -rf ${BKCHECKLINK}.old  2>&1 | tee -a /tmp/BKlog
            mv -f ${BKCHECKLINK} ${BKCHECKLINK}.old  2>&1 | tee -a /tmp/BKlog
        else
            bkwarn ${BKCHECKLINK} exists, but is neither a symlink, a directory
            bkwarn nor a file.  This script was expecting to find a symbolic
            bkwarn link. Please rename it, move it or delete it.  It will be 
            bkwarn created by this script.  Please fix it and run 
            bkwarn ${BKORIGPARAMS} again.
            exit
        fi
    else
        bkstatus ${BKCHECKLINK} does not exist, no problem, we create it.
    fi
done


cd /usr/include
bkstatus Re-creating /usr/include links
bkstatus /usr/include/asm...
ln -s /usr/src/linux/include/asm asm  2>&1 | tee -a /tmp/BKlog
bkstatus /usr/include/linux...
ln -s /usr/src/linux/include/linux linux  2>&1 | tee -a /tmp/BKlog
bkstatus /usr/include/scsi...
ln -s /usr/src/linux/include/scsi scsi  2>&1 | tee -a /tmp/BKlog
bkstatus Links created.  /usr/src/linux gets created in a moment.

#/usr/src/linux gets created later, once inside "if bkopenfresh=yes" and once
#right after.
#FIXME re-create links in abort routine


#-----------------------------------------------------------------------
bkheader Check drive space
#-----------------------------------------------------------------------
cd /usr/src
BKFREESPACE=`df /usr/src | grep -v '^Filesystem' | \
 gawk --field-separator ' ' '{ print $4 }'`
bkstatus The filesystem containing /usr/src has 
bkstatus ${BKFREESPACE} kilobytes free.

#FIXME implement configurable high and low water marks
if [ ${BKFREESPACE} -lt 45000 ]; then
    if [ "${BKINTERACTIVE}" = "YES" ]; then
        bkwarn I show less than 45M free in the area used to build the 
        bkwarn kernel.  This may or may not be a problem.  If we will be 
        bkwarn erasing or overwriting an old kernel, as little as 15M 
        bkwarn may be enough.  If not, we may need between 25M and 
        bkwarn 60M for the build.  Please decide if this build should 
        bkwarn continue.  If there is enough space, simply press enter.  
        bkwarn If there is not enough space, press Ctrl-C now, free up
        bkwarn some space, and re-run ${BKORIGPARAMS}.
        read BKJUNK
    else
        if [ ${BKFREESPACE} -lt 5000 ]; then
            bkwarn We have less than 5M in the /usr/src partition.
            bkwarn I do not consider this to be enough to continue.  
            bkwarn Please free up some space and re-run ${BKORIGPARAMS}.
            exit
        else
            bkwarn Warning!  We have between 5M and 45M in the /usr/src
            bkwarn partition, but the current configuration asks for no 
            bkwarn interaction with the user.  We will push on and hope that
            bkwarn we do not run out of space.
        fi
    fi
else
    bkstatus More than 45M free in /usr/src, probably OK.
fi



bkstatus This will install, patch, and compile linux ${BKKERNELTOBUILD}




#-----------------------------------------------------------------------
bkheader Check if we have source files, get them if we do not.
#-----------------------------------------------------------------------
cd /usr/src
if [ "${BKOPENFRESH}" = "YES" ]; then
    if [ -f ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.gz ]; then
        bkstatus ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.gz found.
    elif [ -f ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar ]; then
        bkstatus ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar found.
    elif [ -f ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.bz2 ]; then
        bkstatus ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.bz2 found.
    elif [ -f ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tgz ]; then
        bkstatus ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tgz found.
    elif [ "${BKAUTOGET}" = "YES" ]; then
#FIXME How to handle partial downloads?
#FIXME Check for existance of file w/ right size before autodownload

        bksplitversion ${BKKERNELTOBUILD}
        bkstatus Kernel does not exist here. We will go get it.
        bkstatus Opening anonymous connection to ftp.kernel.org
        bkstatus Attempting to download linux-${BKKERNELTOBUILD}.tar.gz
        bkstatus from pub/linux/kernel/v${VERSION}.${PATCHLEVEL}
        #FIXME Someday.... echo get patch-${BKKERNELTOBUILD}.gz
        #FIXME Get file size for later check of successful download

        cd ${BKSOURCEDIR}
        #Remember that only tabs are stripped from the beginning of 
        #"here document" lines.
        BKTIMEBASE=${SECONDS}
        ftp -n <<-EOTEXT  2>&1 | tee -a /tmp/BKlog
		open ftp.kernel.org
		user anonymous ${USER}@${HOSTNAME}
		cd pub/linux/kernel/v${VERSION}.${PATCHLEVEL}
		binary
		hash
		prompt
		lcd ${BKSOURCEDIR}
		get linux-${BKKERNELTOBUILD}.tar.gz
		close
		quit
	EOTEXT
        if [ -f ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.gz ]; then
            bkstatus Download took $[${SECONDS}-${BKTIMEBASE}] seconds.
            bkstatus ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.gz
            bkstatus Successfully downloaded.
        else
            bkstatus Download attempt took $[${SECONDS}-${BKTIMEBASE}] seconds.
            bkwarn ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.gz
            bkwarn was not successfully downloaded.
            bkwarn Is your Internet connection down?
            bkwarn Out of disk space?
            bkwarn ftp.kernel.org overloaded?
            exit
        fi
    else
        bkwarn I cannot find ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.gz
        bkwarn Please place the file there, or edit the
        bkwarn BKSOURCEDIR variable in ~/.bkrc, and restart.
        bkwarn .tar, .tgz, and .tar.bz2 files are acceptable.
        bkwarn If you would like me to automatically get the newest 
        bkwarn kernel, try 
        bkwarn ${BKORIGPARAMS} NEWESTSTABLE 
        bkwarn or 
        bkwarn ${BKORIGPARAMS} NEWESTBETA
        bkwarn or set BKAUTOGET=YES in ~/.bkrc and rerun ${BKORIGPARAMS}
        exit
    fi
else
    bkstatus Current configuration chooses not to open a fresh kernel.
fi


#FIXME move to sanity checks
cd /usr/src
if [ "${BKINTERACTIVE}" != "YES" ]; then
    #-----------------------------------------------------------------------
    bkheader Make sure we have configuration files
    #-----------------------------------------------------------------------
    #I only require the files to exist if user interaction is turned off.
    if [ ! -f /usr/src/linux-${BKKERNELTOBUILD}/.config ] && \
       [ ! -f /usr/src/configs/.config.${BKKERNELTOBUILD} ]; then
        bkwarn Interactive mode is off, but I cannot find a kernel .config
        bkwarn file in either /usr/src/linux-${BKKERNELTOBUILD} or in 
        bkwarn /usr/src/configs/.config.${BKKERNELTOBUILD} to reuse.  You must 
        bkwarn re-enable interactive mode in ~/.bkrc
        bkwarn and re-run ${BKORIGPARAMS}
        exit
    else
        bkstatus Kernel .config or backup exists.
    fi #if linux .config (and backup) are missing
    # Missing .version is not a problem, we do not check for it.
    if [ ! "${BKPCMCIATOBUILD}" = "NO" ]; then
        if [ ! -f /usr/src/pcmcia-cs-${BKPCMCIATOBUILD}/config.mk ] && \
           [ ! -f /usr/src/configs/config.mk.${BKPCMCIATOBUILD} ]; then
            bkwarn Interactive mode is off, but I cannot find a pcmcia-cs 
            bkwarn config.mk in either /usr/src/pcmcia-cs-${BKPCMCIATOBUILD} 
            bkwarn or /usr/src/configs/config.mk.${BKPCMCIATOBUID} for reuse.  
            bkwarn You should re-enable interactive mode in ~/.bkrc
            bkwarn and re-run ${BKORIGPARAMS}
            exit
        else
            bkstatus Pcmcia config.mk or backup exists.
	fi #if pcmcia config.mk (and backup) are missing
        if [ ! -f /usr/src/pcmcia-cs-${BKPCMCIATOBUILD}/config.out ] && \
           [ ! -f /usr/src/configs/config.out.${BKPCMCIATOBUILD} ]; then
            bkwarn Interactive mode is off, but I cannot find a pcmcia-cs 
            bkwarn config.out in either /usr/src/pcmcia-cs-${BKPCMCIATOBUILD}
            bkwarn or /usr/src/configs/config.out.${BKPCMCIATOBUILD} for reuse.  
            bkwarn You should re-enable interactive mode in ~/.bkrc
            bkwarn and re-run ${BKORIGPARAMS}
            exit
        else
            bkstatus Pcmcia config.out or backup exists.
	fi #if pcmcia config.out (and backup) are missing
    fi #if building pcmcia
fi #if Interactive!=YES

if [ "${BKOPENFRESH}" = "YES" ]; then
#-----------------------------------------------------------------------
bkheader Remove old source, open new source, apply patches, rename tree
#-----------------------------------------------------------------------
    cd /usr/src
    if [ -d linux-${BKKERNELTOBUILD} ]; then
        if [ -f linux-${BKKERNELTOBUILD}/.config ]; then
            bkstatus Backing up .config
            mv -b -f linux-${BKKERNELTOBUILD}/.config configs/.config.${BKKERNELTOBUILD}  2>&1 | tee -a /tmp/BKlog
        else
            bkstatus No .config to back up, no problem
        fi
        if [ -f linux-${BKKERNELTOBUILD}/.version ]; then
            bkstatus Backing up .version
            mv -f linux-${BKKERNELTOBUILD}/.version configs/.version.${BKKERNELTOBUILD}  2>&1 | tee -a /tmp/BKlog
        else
            bkstatus No .version to back up, no problem
        fi
        if [ -f /bin/rpm ]; then
            bkstatus I am running on a RedHat 3 or greater system.
            bkstatus I will first try to remove any RedHat installed
            bkstatus kernel source files, but not an actual kernel
            #This rm uses a complete path, so we don't need to check pwd.
#FIXME just use rpm -q kernel-source = "package kernel-source is not installed"
            rm -f /tmp/BKrpmqa  2>&1 | tee -a /tmp/BKlog
            rpm -qa >/tmp/BKrpmqa  2>&1 | tee -a /tmp/BKlog
            if grep kernel-source /tmp/BKrpmqa; then 
                bkstatus kernel-source.rpm is installed, removing
                rpm --erase kernel-source  2>&1 | tee -a /tmp/BKlog
            else
                bkstatus kernel-source.rpm is not installed, no problem.
            fi
#FIXME likewise
            if grep kernel-headers /tmp/BKrpmqa; then 
                bkstatus kernel-headers.rpm is installed, removing
                rpm --erase kernel-headers  2>&1 | tee -a /tmp/BKlog
            else
                bkstatus kernel-headers.rpm is not installed, no problem.
            fi
            bkstatus I do not touch kernel, kernel-modules or 
            bkstatus pcmcia-cs rpms as they might be needed to 
            bkstatus boot into an old kernel.
        fi
        # Even if we toasted the RedHat sources, we still clean up in case
        # files are left over.
        bkstatus Directory linux-${BKKERNELTOBUILD} found, removing.
        bkstatus This may take a minute...
        #These rm's use complete paths, so we don't need to check pwd.
        rm -rf /usr/src/linux-${BKKERNELTOBUILD}/*  2>&1 | tee -a /tmp/BKlog
        rm -rf /usr/src/linux-${BKKERNELTOBUILD}/.[a-zA-Z0-9]*  2>&1 | tee -a /tmp/BKlog
        rm -f /usr/src/linux  2>&1 | tee -a /tmp/BKlog
        rmdir /usr/src/linux-${BKKERNELTOBUILD}  2>&1 | tee -a /tmp/BKlog
    else
        bkstatus No existing linux-${BKKERNELTOBUILD}, no files to delete, no problem.
    fi


    bkstatus Installing new version of kernel source tree.
    bkstatus Creating linux- ${BKKERNELTOBUILD} directory
    mkdir --parents linux-${BKKERNELTOBUILD}  2>&1 | tee -a /tmp/BKlog
    bkstatus Creating /usr/src/linux symbolic link
    ln -sf linux-${BKKERNELTOBUILD} linux  2>&1 | tee -a /tmp/BKlog

    bkstatus Opening up source tar, may take a minute...
    bkstatus Wouldnt a cup of coffee be nice right about now?

    BKTIMEBASE=${SECONDS}
    if [ -f ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.gz ]; then
        bkstatus Opening ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.gz
        ${BKLOAD} tar -xpzf ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.gz  2>&1 | tee -a /tmp/BKlog
    elif [ -f ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.bz2 ]; then
        bkstatus Opening ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.bz2
        ${BKLOAD} cat ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar.bz2        | \
        ${BKLOAD} bunzip2                                                   | \
        ${BKLOAD} tar -xpf - 2>&1 | tee -a /tmp/BKlog
    elif [ -f ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar ]; then
        bkstatus Opening ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar
        ${BKLOAD} tar -xpf ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tar  2>&1 | tee -a /tmp/BKlog
    elif [ -f ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tgz ]; then
        bkstatus Opening ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tgz
        ${BKLOAD} tar -xpzf ${BKSOURCEDIR}linux-${BKKERNELTOBUILD}.tgz  2>&1 | tee -a /tmp/BKlog
    fi
    bkstatus Opening the source tar took $[${SECONDS}-${BKTIMEBASE}] seconds.


    BKFREESPACE=`df /usr/src | grep -v '^Filesystem' | \
     gawk --field-separator ' ' '{ print $4 }'`
    bkstatus After opening the new kernel, the filesystem containing 
    bkstatus /usr/src has ${BKFREESPACE} kilobytes free.

    if [ ${BKFREESPACE} -lt 2000 ]; then
        if [ "${BKINTERACTIVE}" = "YES" ]; then
            bkwarn I show less than 2M free in the area used to build the 
            bkwarn kernel.  This may or may not be a problem.  If there is 
            bkwarn a severely low amount of space, such as less than 100K,
            bkwarn there may not have been enough space to open the kernel
            bkwarn source.  Please decide if this build should 
            bkwarn continue.  If there is enough space, simply press enter.  
            bkwarn If there is not enough space, press Ctrl-C now, free up
            bkwarn some space, and re-run ${BKORIGPARAMS}
            read BKJUNK
        else
            if [ ${BKFREESPACE} -lt 100 ]; then
                bkwarn We have less than 100K in the /usr/src partition.
                bkwarn I do not consider this to be enough to continue.  
                bkwarn Please free up some space and re-run ${BKORIGPARAMS}
                exit
            else
                bkwarn Warning!  We have between 100K and 2M in the /usr/src
                bkwarn partition, but the current configuration asks for no 
                bkwarn interaction with the user.  We will push on and hope that
                bkwarn we do not run out of space.
            fi
        fi
    else
        bkstatus More than 2M free in /usr/src, probably OK.
    fi



    if [ -f configs/.config.${BKKERNELTOBUILD} ]; then
        bkstatus Restoring .config
        cp configs/.config.${BKKERNELTOBUILD} linux-${BKKERNELTOBUILD}/.config  2>&1 | tee -a /tmp/BKlog
    else
        bkstatus This kernel version does not have a pre-existing .config  .
        bkstatus We will try to get the previous .config from this series.

        bksplitversion ${BKKERNELTOBUILD}
        case ${VERSION}.${PATCHLEVEL} in
        1.0)	BKLASTBUILT=${BKLASTBUILT10}	;;
        1.1)	BKLASTBUILT=${BKLASTBUILT11}	;;
        1.2)	BKLASTBUILT=${BKLASTBUILT12}	;;
        1.3)	BKLASTBUILT=${BKLASTBUILT13}	;;
        2.0)	BKLASTBUILT=${BKLASTBUILT20}	;;
        2.1)	BKLASTBUILT=${BKLASTBUILT21}	;;
        2.2)	BKLASTBUILT=${BKLASTBUILT22}	;;
        2.3)	BKLASTBUILT=${BKLASTBUILT23}	;;
        2.4)	BKLASTBUILT=${BKLASTBUILT24}	;;
        2.5)	BKLASTBUILT=${BKLASTBUILT25}	;;
        2.6)	BKLASTBUILT=${BKLASTBUILT26}	;;
        2.7)	BKLASTBUILT=${BKLASTBUILT27}	;;
        3.0)	BKLASTBUILT=${BKLASTBUILT30}	;;
        3.1)	BKLASTBUILT=${BKLASTBUILT31}	;;
        3.2)	BKLASTBUILT=${BKLASTBUILT32}	;;
        3.3)	BKLASTBUILT=${BKLASTBUILT33}	;;
        4.0)	BKLASTBUILT=${BKLASTBUILT40}	;;
        4.1)	BKLASTBUILT=${BKLASTBUILT41}	;;


        *)
            bkwarn I am not aware of the kernel series ${VERSION}.${PATCHLEVEL}
            bkwarn Please get a new version of the buildkernel script at 
            bkwarn http://www.pobox.com/~wstearns
#FIXME later implement a default to pull from?
            BKLASTBUILT=""
            ;;
        esac

        if [ -f configs/.config.${BKLASTBUILT} ]; then
            bkstatus Restoring .config from version ${BKLASTBUILT}
            cp configs/.config.${BKLASTBUILT} linux-${BKKERNELTOBUILD}/.config  2>&1 | tee -a /tmp/BKlog
        else
            bkstatus Sorry, cannot find a previous .config from this series either.
	fi
    fi
    if [ -f configs/.version.${BKKERNELTOBUILD} ]; then
        bkstatus Restoring .version
	cp configs/.version.${BKKERNELTOBUILD} linux-${BKKERNELTOBUILD}/.version  2>&1 | tee -a /tmp/BKlog
    else
        bkstatus No .version to restore, no problem
    fi

    if [ -d kpatches-${BKKERNELTOBUILD} ]; then
        if [ ! "${BKVERBOSE}" = "NO" ]; then
            bkstatus Patching kernel.
            bkstatus Here are the patches we will attempt to use.
            echo ----------------------------------------------------------------------- 2>&1 | tee -a /tmp/BKlog
            cd /usr/src/kpatches-${BKKERNELTOBUILD}
            for BKCHECKPATCH in 00 0 01 1 02 2 03 3 04 4 05 5 06 6 07 7 08 8 09 9 \
                                10 11 12 13 14 15 16 17 18 19 20 ; do
                if [ -e /usr/src/kpatches-${BKKERNELTOBUILD}/${BKCHECKPATCH} ]; then
                    ls -l /usr/src/kpatches-${BKKERNELTOBUILD}/${BKCHECKPATCH}  2>&1 | tee -a /tmp/BKlog
                fi
            done
            echo ----------------------------------------------------------------------- 2>&1 | tee -a /tmp/BKlog
        fi #Verbose != NO
        # _someone_ is going to use 0-9,10-20 instead of 00-20.  We deal with it.
        # We do it this way to ensure that patches are applied in numerical order.

        cd /usr/src
        BKTIMEBASE=${SECONDS}
        for BKPATCH in 00 0 01 1 02 2 03 3 04 4 05 5 06 6 07 7 08 8 09 9  \
                       10 11 12 13 14 15 16 17 18 19 20                   ; do
            if [ -f kpatches-${BKKERNELTOBUILD}/${BKPATCH} ]; then
                bkheader Applying patch ${BKPATCH}
                ls -al kpatches-${BKKERNELTOBUILD}/${BKPATCH}  2>&1 | tee -a /tmp/BKlog

#FIXME Automatically uncompress .gz and .Z patches if compressed
#FIXME handle .bz2
#Held for a future version...sigh... Gotta freeze the code sometime.
#
#Redo this until you get diff text; there could be a .gz uuencoded
#handle uuencode too.  Tar?  Well, no.
#                if [ `file kpatches-${BKKERNELTOBUILD}/${BKPATCH} | \
#                 grep "\'diff\' output text" | wc -l | sed -e s/\ //g` \
#                 = 1 ]; then
#                    bkstatus This is a straight diff file, no compression.
#                elif [ `file kpatches-${BKKERNELTOBUILD}/${BKPATCH} | \
#                 grep "gzip compressed data" | wc -l | sed -e s/\ //g` \
#                 = 1 ]; then
#                    bkstatus This is a gzipped .gz file
#                elif [ `file kpatches-${BKKERNELTOBUILD}/${BKPATCH} | \
#                 grep "compress\'d data" | wc -l | sed -e s/\ //g` \
#                 = 1 ]; then
#                    bkstatus This is a compressed .Z file
#
#                fi


                ${BKLOAD} patch -s --remove-empty-files -p0 <kpatches-${BKKERNELTOBUILD}/${BKPATCH}  2>&1 | tee -a /tmp/BKlog
                if [ "`find /usr/src/linux-${BKKERNELTOBUILD}/ -iname '*.rej' \
                 | wc -l | sed -e s/\ //g`" = "0" ]; then
                    bkstatus No rejects from this patch
                else
                    bkwarn Patching with
                    ls -al kpatches-${BKKERNELTOBUILD}/${BKPATCH}  2>&1 | tee -a /tmp/BKlog
                    bkwarn created the following .rej reject files
                    bkwarn 
                    find /usr/src/linux-${BKKERNELTOBUILD}/ -iname '*.rej'  2>&1 | tee -a /tmp/BKlog
                    bkwarn
                    bkwarn Please fix and start me again.  If you are not 
                    bkwarn sure of how to fix, you might try removing
                    bkwarn /usr/src/kpatches-${BKKERNELTOBUILD}/${BKPATCH}
                    bkwarn and running ${BKORIGPARAMS} again.
#FIXME onetime: set BKOPENFRESH=YES, tell user.
                    exit
                fi
                BKPATCHESAPPLIED=YES
            fi
        done
        if [ "${BKPATCHESAPPLIED}" = "YES" ]; then
            bkheader All patches applied
	    bkstatus All patches applied successfully with no rejects.
            bkstatus Patching the source took $[${SECONDS}-${BKTIMEBASE}] seconds.

            #Thanks to the KERNEL-HOWTO for this step...
            bkstatus Removing patch remnants, the .orig files.
            #The find command returns complete paths so we do not need to check pwd.
            find /usr/src/linux-${BKKERNELTOBUILD} -name '*.orig' \
             -exec rm -f {} ';'  2>&1 | tee -a /tmp/BKlog

            BKFREESPACE=`df /usr/src | grep -v '^Filesystem' | \
             gawk --field-separator ' ' '{ print $4 }'`
            bkstatus After applying patches, the filesystem containing 
            bkstatus /usr/src has ${BKFREESPACE} kilobytes free.

            if [ ${BKFREESPACE} -lt 2000 ]; then
                if [ "${BKINTERACTIVE}" = "YES" ]; then
                    bkwarn I show less than 2M free in the area used to build the 
                    bkwarn kernel.  This may or may not be a problem.  If there is 
                    bkwarn a severely low amount of space, such as less than 100K,
                    bkwarn there may not have been enough space to apply the patches.
                    bkwarn Please decide if this build should 
                    bkwarn continue.  If there is enough space, simply press enter.  
                    bkwarn If there is not enough space, press Ctrl-C now, free up
                    bkwarn some space, and re-run ${BKORIGPARAMS}
                    read BKJUNK
                else
                    if [ ${BKFREESPACE} -lt 100 ]; then
                        bkwarn We have less than 100K in the /usr/src partition.
                        bkwarn I do not consider this to be enough to continue.  
                        bkwarn Please free up some space and re-run ${BKORIGPARAMS}
                        exit
                    else
                        bkwarn Warning!  We have between 100K and 2M in the /usr/src
                        bkwarn partition, but the current configuration asks for no 
                        bkwarn interaction with the user.  We will push on and hope that
                        bkwarn we do not run out of space.
                    fi #BKFREESPACE lt 100K
                fi #BKINTERACTIVE=YES
            else
                bkstatus More than 2M free in /usr/src, probably OK.
            fi #BKFREESPACE lt 2M
        else
            bkheader No patches applied
            bkwarn kpatches-${BKKERNELTOBUILD} exists, but no files with names
            bkwarn 00 to 20.  No patches applied.  Problem?
            bkwarn If you have no patches to apply, please remove
            bkwarn directory /usr/src/kpatches-${BKKERNELTOBUILD}.
            bkwarn No need to exit, non-fatal error.
        fi
    else
        bkstatus No kpatches-${BKKERNELTOBUILD} dir.
        bkstatus no patches to apply, no problem.
    fi

    if [ ! -f /usr/src/linux-${BKKERNELTOBUILD}/Makefile ]; then
        bkwarn Hmmm... there does not seem to be a Makefile in
        bkwarn /usr/src/linux-${BKKERNELTOBUILD}/.  That would seem to 
        bkwarn indicate that the source files are incomplete or 
        bkwarn missing, or one of the patches removed the Makefile.  
        bkwarn Please check on this and run 
        bkwarn ${BKORIGPARAMS} again.
#FIXME onetime: set BKOPENFRESH=YES, tell user
        exit
    fi #if linux Makefile exists

    cd /usr/src
    if [ "${BKPATCHESAPPLIED}" = "YES" ]; then
        bkstatus Checking if we patched to a higher version kernel

        eval `cat /usr/src/linux-${BKKERNELTOBUILD}/Makefile | \
         grep -E '^VERSION|^PATCHLEVEL|^SUBLEVEL' | \
         tr a-z A-Z | \
         sed -e 's/\ //g'`

        BKNEWVER=${VERSION}.${PATCHLEVEL}.${SUBLEVEL}
        if [ "${BKNEWVER}" = ".." ]; then 
            bkwarn BKNEWVER=.. - script error.
#FIXME remove after one final check
            bkwarn This script was unable to get the correct VERSION, 
            bkwarn PATCHLEVEL, and SUBLEVEL fields from 
            bkwarn /usr/src/linux-${BKKERNELTOBUILD}/Makefile
            bkwarn If you feel so inclined, would you help the 
            bkwarn author by letting him know why?
            bkwarn email to Bill Stearns, 
            bkwarn wstearns@pobox.com.  Thanks.
            exit
        else
            bkstatus The new version appears to be ${BKNEWVER}
        fi #If BKNEWVER=..
        if [ "${BKNEWVER}" = "${BKKERNELTOBUILD}" ]; then
            bkstatus No change in base kernel version from patching, no problem.
        else
            bkstatus Kernel version changed from ${BKKERNELTOBUILD} to ${BKNEWVER}.
            if [ -d /usr/src/linux-${BKNEWVER} ]; then
                bkstatus Directory linux-${BKNEWVER} found, removing.
                bkstatus This may take a minute...
                #These rm's use complete paths, so we don't need to check pwd.
                rm -rf /usr/src/linux-${BKNEWVER}/*  2>&1 | tee -a /tmp/BKlog
                rm -rf /usr/src/linux-${BKNEWVER}/.[a-zA-Z0-9]*  2>&1 | tee -a /tmp/BKlog
                rmdir /usr/src/linux-${BKNEWVER}  2>&1 | tee -a /tmp/BKlog
            fi
            bkstatus Renaming source tree to match its correct version:
            bkstatus ${BKKERNELTOBUILD} to ${BKNEWVER}
            mv /usr/src/linux-${BKKERNELTOBUILD} /usr/src/linux-${BKNEWVER}  2>&1 | tee -a /tmp/BKlog
            #This rm uses a complete path, so we don't need to check pwd.
            rm -f /usr/src/linux  2>&1 | tee -a /tmp/BKlog
            ln -s linux-${BKNEWVER} linux  2>&1 | tee -a /tmp/BKlog
            BKKERNELTOBUILD=${BKNEWVER}
        fi #End of if versions not the same
    else
        bkstatus No patches applied, we cannot have patched to a higher version.
    fi #End of if BKPATCHESAPPLIED=YES
fi #End of if BKOPENFRESH=YES

cd /usr/src
#Make sure the /usr/src/linux link is created even if we did not open fresh
if [ -L /usr/src/linux ]; then
    bkstatus Removing symlink /usr/src/linux
    #We toast it so the following ln will work correctly.
    #This rm uses a complete path, so we don't need to check pwd.
    rm -f /usr/src/linux
fi
#/usr/src/linux should _not_ exist at this point, so we should have no 
#problem with creating links inside the linux directory.
bkstatus Creating symlink /usr/src/linux
ln -sf linux-${BKKERNELTOBUILD} linux  2>&1 | tee -a /tmp/BKlog

if [ ! -f /usr/src/linux-${BKKERNELTOBUILD}/Makefile ]; then
    bkwarn Hmmm... there does not seem to be a Makefile in
    bkwarn /usr/src/linux-${BKKERNELTOBUILD}/.  That would seem to 
    bkwarn indicate that the source files are incomplete or 
    bkwarn missing.  Please check on this and run 
    bkwarn ${BKORIGPARAMS} again.
#FIXME onetime: set BKOPENFRESH=YES, tell user
    exit
fi




#-----------------------------------------------------------------------
bkheader Removing code for other architectures
#-----------------------------------------------------------------------
cd /usr/src/linux-${BKKERNELTOBUILD}/arch
if [ ! "`pwd`" = "/usr/src/linux-${BKKERNELTOBUILD}/arch" ]; then
    bkwarn We were not able to sucessfully go to the 
    bkwarn /usr/src/linux-${BKKERNELTOBUILD}/arch directory.  This could
    bkwarn be dangerous as we are about to delete a number of directories.
    bkwarn Exiting.
    exit
fi
for BKARCHI in *; do
    if [ "${HOSTTYPE}" = "${BKARCHI}" ]; then
        bkstatus Keeping ${BKARCHI}
    else
        if [ -d ${BKARCHI} ]; then 
            bkstatus Removing ${BKARCHI}
            #These rm's use complete paths, so we don't need to check pwd.
            #We have already checked that we are, in fact, in the 
            #/usr/src/linux-version/arch directory anyways.
            ${BKLOAD} rm -rf /usr/src/linux-${BKKERNELTOBUILD}/arch/${BKARCHI}/*  2>&1 | tee -a /tmp/BKlog
            ${BKLOAD} rm -rf /usr/src/linux-${BKKERNELTOBUILD}/arch/${BKARCHI}/.[a-zA-Z0-9]*  2>&1 | tee -a /tmp/BKlog
            rmdir /usr/src/linux-${BKKERNELTOBUILD}/arch/${BKARCHI}  2>&1 | tee -a /tmp/BKlog
        else 
            bkstatus no ${BKARCHI} directory
        fi

        if [ -d ../include/asm-${BKARCHI} ]; then 
            bkstatus Removing asm-${BKARCHI}
            #These rm's use complete paths, so we don't need to check pwd.
            ${BKLOAD} rm -rf /usr/src/linux-${BKKERNELTOBUILD}/include/asm-${BKARCHI}/*  2>&1 | tee -a /tmp/BKlog
            ${BKLOAD} rm -rf /usr/src/linux-${BKKERNELTOBUILD}/include/asm-${BKARCHI}/.[a-zA-Z0-9]*  2>&1 | tee -a /tmp/BKlog
            rmdir /usr/src/linux-${BKKERNELTOBUILD}/include/asm-${BKARCHI}   2>&1 | tee -a /tmp/BKlog
        else 
            bkstatus no asm-${BKARCHI}
        fi
    fi
done
unset BKARCHI



cd /usr/src/linux-${BKKERNELTOBUILD}
#-----------------------------------------------------------------------
bkheader Setting kernel configuration
#-----------------------------------------------------------------------
if [ "`cat Makefile | sed -e s/\ //g | grep 'SMP=' | \
 wc -l | sed -e s/\ //g`" = "1" ]; then
    bkstatus Makefile has a reference to "SMP="

    if [ "`cat /proc/cpuinfo | grep ^processor | wc -l | \
     sed -e s/\ //g`" = "1" ]; then
        bkstatus This machine has a single processor.  We will set the 
        bkstatus Makefile to build a uniprocessor kernel.  
        if [ "${BKINTERACTIVE}" = "YES" ]; then
            bkstatus You can change this later if you like.
        else
            bkstatus Because user has requested no interaction, there will not
            bkstatus be an opportunity to change this.
        fi
        cat Makefile | sed -e 's/^[# \t]*SMP[ \t]*=[ \t]*1[ \t]*$/# SMP = 1/' \
         >Makefile.tmp
    else
        bkstatus This machine has more than one processor.  We will set 
        bkstatus the Makefile to build an SMP kernel.  
        if [ "${BKINTERACTIVE}" = "YES" ]; then
            bkstatus You can change this later if you like.
        else
            bkstatus Because user has requested no interaction, there will not
            bkstatus be an opportunity to change this.
        fi
        cat Makefile | sed -e 's/^[# \t]*SMP[ \t]*=[ \t]*1[ \t]*$/SMP = 1/' \
         >Makefile.tmp
    fi #if there is a single processor
    mv -f Makefile.tmp Makefile
else
    bkstatus Makefile has no reference to "SMP=".  This kernel only 
    bkstatus supports uniprocessor mode.
fi #If there is a reference to SMP=



#FIXME reinstate following if when we can work around not running config.
if [ "${BKINTERACTIVE}" = "YES" ]; then
    if [ ! "${BKVERBOSE}" = "NO" ]; then
        bkstatus About to let you manually set .config options
        bkstatus When done, save changes and exit.
        bkstatus NOTE - If you do not have any changes to make, 
        bkstatus simply save and exit.
        bkstatus Please press enter when ready to edit Makefile.
        read BKJUNK
    fi
    ${EDITOR} Makefile
    make ${BKMAKETYPE}
    cp -b -f /usr/src/linux-${BKKERNELTOBUILD}/.config /usr/src/configs/.config.${BKKERNELTOBUILD}  2>&1 | tee -a /tmp/BKlog
else
    bkstatus No configuration will be manually set as Interactivity is off.
    #We run menuconfig, but feed it 'x' to exit and 'y' to save changes.
#FIXME handle this in a way that does not require x or ncurses.
    make menuconfig <<EOTEXT
xy
EOTEXT
#    #FIXME - what _really_ has to be done?
#    #Make symlinks gets run as part of the make {config|xconfig|menuconfig} 
#    #process, but in non-interactive mode these don't get run.  Run it 
#    #manually now.
#    make symlinks
#    #make noconfig
fi





#-----------------------------------------------------------------------
bkheader Main kernel build.
#-----------------------------------------------------------------------
cd /usr/src/linux-${BKKERNELTOBUILD}
bkstatus Making dependencies
BKTIMEBASE=${SECONDS}
${BKLOAD} make dep  2>&1 | tee -a /tmp/BKlog
bkstatus Creating the dependencies took $[${SECONDS}-${BKTIMEBASE}] seconds.

if [ "${BKMAKECLEANBEFORE}" = "YES" ]; then
    bkstatus Cleaning out old compiled code for a fresh compile
    ${BKLOAD} make clean  2>&1 | tee -a /tmp/BKlog
else
    bkstatus Current configuration chooses not to make clean, no problem.
fi

if [ -f /usr/src/linux-${BKKERNELTOBUILD}/arch/${HOSTTYPE}/boot/${BKBUILDTYPE} ]; then
    rm -f /usr/src/linux-${BKKERNELTOBUILD}/arch/${HOSTTYPE}/boot/${BKBUILDTYPE}
fi
bkstatus Compiling actual kernel
BKTIMEBASE=${SECONDS}
${BKLOAD} make ${BKBUILDTYPE} MAKE="make -j ${BKNUMBUILDS}"  2>&1 | tee -a /tmp/BKlog
#FIXME Integrate gcc parameter filter
bkstatus Compiling the base kernel took $[${SECONDS}-${BKTIMEBASE}] seconds.


if [ ! -f /usr/src/linux-${BKKERNELTOBUILD}/arch/${HOSTTYPE}/boot/${BKBUILDTYPE} ]; then
    #If anything but a bzImage or bzdisk failed, we try that now.
    bkwarn Building ${BKBUILDTYPE} failed to create a kernel.
    BKFREESPACE=`df /usr/src | grep -v '^Filesystem' | \
     gawk --field-separator ' ' '{ print $4 }'`
    if [ ${BKFREESPACE} -lt 2000 ]; then
        bkwarn The filesystem where the build took place has
        bkwarn ${BKFREESPACE} kilobytes free.
        bkwarn This may have been a factor in the failed build.
    fi #if lt 2M free.
    if [ "`echo ${BKBUILDTYPE} | cut -b 1`" = "b" ]; then
        bkwarn Since we already tried to build a ${BKBUILDTYPE} kernel, we
        bkwarn do not have another build type to try automatically.  Please
        bkwarn look at any above error messages to see why the build failed.
        bkwarn Then re-run ${BKORIGPARAMS}
#FIXME onetime: set BKOPENFRESH=YES, tell user
        exit
    else
        bkstatus On the chance that the previous build failed because the kernel
        bkstatus was too big, we will retry the build, this time using 
        bkstatus b${BKBUILDTYPE} as the target rather than the ${BKBUILDTYPE}
        bkstatus we just tried.
        BKBUILDTYPE=b${BKBUILDTYPE}
        bkstatus Retrying to build actual kernel, this time as ${BKBUILDTYPE}

        if [ -f /usr/src/linux-${BKKERNELTOBUILD}/arch/${HOSTTYPE}/boot/${BKBUILDTYPE} ]; then
            rm -f /usr/src/linux-${BKKERNELTOBUILD}/arch/${HOSTTYPE}/boot/${BKBUILDTYPE}
        fi
        BKTIMEBASE=${SECONDS}
        ${BKLOAD} make ${BKBUILDTYPE} MAKE="make -j ${BKNUMBUILDS}"  2>&1 | tee -a /tmp/BKlog
        bkstatus Second attempt at base kernel build took $[${SECONDS}-${BKTIMEBASE}] seconds.
        if [ ! -f /usr/src/linux-${BKKERNELTOBUILD}/arch/${HOSTTYPE}/boot/${BKBUILDTYPE} ]; then
            bkwarn Second attempt to build ${BKBUILDTYPE} kernel also failed.
            bkwarn Please look at any above error messages to see why the build failed.
            bkwarn Please check and rerun ${BKORIGPARAMS}
            cd /usr/src/linux-${BKKERNELTOBUILD}/arch/${HOSTTYPE}/boot
#FIXME onetime: set BKOPENFRESH=YES, tell user
            exit
        else
            bkstatus Second kernel build succeeded.
            bkstatus /usr/src/linux-${BKKERNELTOBUILD}/arch/${HOSTTYPE}/boot/${BKBUILDTYPE} exists.
        fi
    fi
else
    bkstatus First build succeeded.
    bkstatus /usr/src/linux-${BKKERNELTOBUILD}/arch/${HOSTTYPE}/boot/${BKBUILDTYPE} exists.
fi
#We get here if the kernel existed after the first build or the second build
#succeeded.







cd /usr/src/linux-${BKKERNELTOBUILD}

eval `cat /usr/src/linux-${BKKERNELTOBUILD}/.config | \
 grep 'CONFIG_MODULES' | tr a-z A-Z`
if [ "${CONFIG_MODULES}" = "Y" ]; then
#-----------------------------------------------------------------------
    bkheader Compiling modules
#-----------------------------------------------------------------------
    BKTIMEBASE=${SECONDS}
    ${BKLOAD} make modules MAKE="make -j ${BKNUMBUILDS}"  2>&1 | tee -a /tmp/BKlog
    bkstatus Creating the kernel modules took $[${SECONDS}-${BKTIMEBASE}] seconds.

    bkstatus Installing modules in module directory
    ${BKLOAD} make modules_install  2>&1 | tee -a /tmp/BKlog
else
    bkstatus Kernel configuration does not include modules, so
    bkstatus no modules built, no problem.
fi

if [ -f /usr/src/linux-${BKKERNELTOBUILD}/.version ]; then
    cp -b -f /usr/src/linux-${BKKERNELTOBUILD}/.version /usr/src/configs/.version.${BKKERNELTOBUILD}  2>&1 | tee -a /tmp/BKlog
fi







#-----------------------------------------------------------------------
bkheader Installing new kernel.
#-----------------------------------------------------------------------
bkstatus Copying kernel and System.map to boot directory
cd /usr/src/linux-${BKKERNELTOBUILD}

# By including .version, BKIMAGEVER hopefully makes a unique filename
BKIMAGEVER=${BKKERNELTOBUILD}-`cat /usr/src/linux-${BKKERNELTOBUILD}/.version`

BKUNIQUEIMAGE=${BKBUILDTYPE}-${BKIMAGEVER}

if [ -f /boot/${BKUNIQUEIMAGE} ]; then
    bkwarn Ugh.  I had attempted to create a unique filename for the new
    bkwarn kernel that was just created.  
fi
while [ -f /boot/${BKUNIQUEIMAGE} ] || [ "${BKUNIQUEIMAGE}" = "" ]; do
    bkwarn Unfortunately, there is already
    bkwarn a file named "${BKUNIQUEIMAGE}" in the /boot/ directory.
    bkwarn Please choose a new filename to use.  To help the process, 
    bkwarn here is a directory listing of the /boot/ directory:
    ls -l /boot/  2>&1 | tee -a /tmp/BKlog
    bkwarn What new file name shall I use that is not already taken?
    bkwarn Please enter just the file name, no path.
    #We only want up to a space, this ignores additional input
    read BKUNIQUEIMAGE BKJUNK
    bkwarn I will try to use ${BKUNIQUEIMAGE}
done

cp -b -f /usr/src/linux-${BKKERNELTOBUILD}/arch/${HOSTTYPE}/boot/${BKBUILDTYPE} /boot/${BKUNIQUEIMAGE}  2>&1 | tee -a /tmp/BKlog

#Well, maybe we overwrite an old System.map.  Is it worth the effort...?
cp -b -f /usr/src/linux-${BKKERNELTOBUILD}/System.map /boot/System.map-${BKIMAGEVER}  2>&1 | tee -a /tmp/BKlog

if [ ! "${BKROOTDEVICE}" = "" ]; then
    bkstatus Forcing root device
    rdev /boot/${BKUNIQUEIMAGE} ${BKROOTDEVICE}  2>&1 | tee -a /tmp/BKlog
fi

bkstatus Telling kernel to mount root read-only
rdev -R /boot/${BKUNIQUEIMAGE} 1  2>&1 | tee -a /tmp/BKlog

case "${BKVIDMODE}" in
"-2")	bkstatus Setting 80x50 line video				;;
"-1")	bkstatus Setting 80x25 line video				;;
*)	bkstatus Setting video mode number ${BKVIDMODE}			;;
esac
rdev -v /boot/${BKUNIQUEIMAGE} ${BKVIDMODE}  2>&1 | tee -a /tmp/BKlog

if [ "${BKCOPYTOFLOPPY}" = "YES" ]; then
    if [ "${BKINTERACTIVE}" = "YES" ]; then
        bkstatus Copying to floppy - make sure a floppy is in the drive,
        if [ ! "`mount | grep '^/dev/fd0' | wc -l | sed -e 's/\ //g'`" = "0" ]; then
            bkwarn WARNING!!!!!!!!!!!!
            bkwarn The floppy appears to be mounted.  If we proceed with
            bkwarn copying the kernel, it will overwrite what is probably a 
            bkwarn floppy with your data.  I STRONGLY recommend that you 
            bkwarn unmount the floppy.  If you wish to do so, switch to another
            bkwarn console, unmount the floppy, place the correct floppy 
            bkwarn in the drive without mounting it, switch back, and
        fi
        if [ ! "${BKVERBOSE}" = "NO" ]; then
            bkstatus press enter when ready.
            read BKJUNK
        fi
        cp /boot/${BKUNIQUEIMAGE} /dev/fd0  2>&1 | tee -a /tmp/BKlog
    else
        bkstatus User has asked for no interaction.  
        if [ ! "`mount | grep '^/dev/fd0' | wc -l | sed -e 's/\ //g'`" = "0" ]; then
            bkwarn WARNING!!!!!!!!!!!!
            bkwarn The floppy appears to be mounted.  If we proceed with
            bkwarn copying the kernel, it will overwrite what is probably a 
            bkwarn floppy with your data.  To avoid a tragedy, this script
            bkwarn WILL NOT copy the kernel to the floppy.  You can copy
            bkwarn /boot/${BKUNIQUEIMAGE} to /dev/fd0 later once you have
            bkwarn unmounted the current floppy and inserted the floppy on 
            bkwarn which the kernel should be placed.  The command
            bkwarn cp /boot/${BKUNIQUEIMAGE} /dev/fd0
            bkwarn will accomplish that task.
        else
            bkstatus Script will blindly try to copy image to a floppy.
            bkstatus I hope there is a floppy in the drive...
            cp /boot/${BKUNIQUEIMAGE} /dev/fd0  2>&1 | tee -a /tmp/BKlog
        fi #floppy mounted
    fi #INTERACTIVE=YES
else
    bkstatus Current configuration does not request making a
    bkstatus bootable floppy, no problem.
fi #copytofloppy=yes

if [ -f /etc/lilo.conf ]; then
    bkstatus setting up lilo.conf, which exists
    cat >>/etc/lilo.conf <<EOTEXT
#The following boot section was added by buildkernel on
#`date`
#Please feel free to move this section, edit it, and remove these comments.
image=/boot/${BKUNIQUEIMAGE}
        label=${BKIMAGEVER}
        root=${BKROOTDEVICE}
        read-only
#End of autoinstall

EOTEXT
    bkstatus Kernel and modules sucessfully installed.
    bkstatus Kernel is in /boot/${BKUNIQUEIMAGE}
    BKLILOIMAGES=`cat /etc/lilo.conf | grep -i '^image' | \
     wc -l | sed -e s/\ //g`
    if [ "${BKINTERACTIVE}" = "YES" ]; then
        bkstatus The build process has added a section to lilo.conf
        bkstatus that will boot the kernel that was just built.  Please
        bkstatus feel free to move or edit this section.  Once you 
        bkstatus have made any changes, please save and exit.
	if [ ${BKLILOIMAGES} -gt 13 ]; then
            bkwarn Your lilo.conf is getting close to the limit of 
            bkwarn 16 image= sections.  Please remove any that are 
            bkwarn no longer needed.
        else
            bkstatus lilo.conf is safely under 13 image lines.
        fi
        if [ ! "${BKVERBOSE}" = "NO" ]; then
            bkstatus Please press enter when ready to edit.
            read BKJUNK
        fi
        ${EDITOR} /etc/lilo.conf
    else
	if [ ${BKLILOIMAGES} -gt 16 ]; then
            bkwarn Your lilo.conf has reached the limit of 
            bkwarn 16 image= sections.  Please remove any that are 
            bkwarn no longer needed.  Any images beyond 16 cannot 
            bkwarn be booted.
        fi
    fi
    bkstatus Installing boot images
    lilo  2>&1 | tee -a /tmp/BKlog
    unset BKLILOIMAGES
else
    bkwarn There is no /etc/lilo.conf.  Are you using a different
    bkwarn boot manager?  The author of this script would like to 
    bkwarn know what boot system you are using so that he could 
    bkwarn find out how to register the new kernel with it.  Please
    bkwarn contact William Stearns at wstearns@pobox.com.
fi



if [ "${BKMAKECLEANAFTER}" = "YES" ]; then
#-----------------------------------------------------------------------
    bkheader Cleaning out kernel build files.
#-----------------------------------------------------------------------
    cd /usr/src/linux-${BKKERNELTOBUILD}
    ${BKLOAD} make clean  2>&1 | tee -a /tmp/BKlog
else
    bkstatus Current configuration chooses to not make clean.
fi




#End of skip over kernel build
#fi





cd /usr/src
if [ "${BKPCMCIATOBUILD}" != "NO" ]; then
#-----------------------------------------------------------------------
    bkheader Building PCMCIA drivers.
#-----------------------------------------------------------------------
    bkstatus Attempting version ${BKPCMCIATOBUILD}
    if [ -f ${BKSOURCEDIR}pcmcia-cs-${BKPCMCIATOBUILD}.tar.gz ]; then
        cd /usr/src
        if [ -d pcmcia-cs-${BKPCMCIATOBUILD} ]; then
            if [ -f pcmcia-cs-${BKPCMCIATOBUILD}/config.mk ]; then
                bkstatus Backing up config.mk
                cp -b -f pcmcia-cs-${BKPCMCIATOBUILD}/config.mk configs/config.mk.${BKPCMCIATOBUILD}  2>&1 | tee -a /tmp/BKlog
            else
                bkstatus No config.mk to back up, no problem.
            fi
            if [ -f pcmcia-cs-${BKPCMCIATOBUILD}/config.out ]; then
                bkstatus Backing up config.out
                cp -b -f pcmcia-cs-${BKPCMCIATOBUILD}/config.out configs/config.out.${BKPCMCIATOBUILD}  2>&1 | tee -a /tmp/BKlog
            else
                bkstatus No config.out to back up, no problem.
            fi
#FIXME Remove once you are sure
#Unfortunately, pcmcia-cs does not seem to do well if we are compiling a 
#different kernel version than last time.  We toast it.
#if [ "${BKMAKECLEANBEFORE}" = "YES" ]; then
            bkstatus Removing existing pcmcia-cs-${BKPCMCIATOBUILD} directory.
            #This rm uses a complete path, so we don't need to check pwd.
            rm -rf /usr/src/pcmcia-cs-${BKPCMCIATOBUILD}  2>&1 | tee -a /tmp/BKlog
#else
#    bkstatus Not removing pcmcia-cs-${BKPCMCIATOBUILD} because MAKECLEANBEFORE ne YES
#fi
        else
            bkstatus No existing pcmcia-cs-${BKPCMCIATOBUILD} to remove.
        fi
        mkdir --parents pcmcia-cs-${BKPCMCIATOBUILD}  2>&1 | tee -a /tmp/BKlog


#FIXME Move up to download after kernel download
#FIXME Implement pcmcia-cs autodownload
#FIXME Check for existance of file w/ right size before autodownload
#elif [ "${BKAUTOGET}" = "YES" ]; then
#        bkstatus Pcmcia-cs source does not exist here. We will go get it.
#        bkstatus Opening anonymous connection to hyper.stanford.edu
#        bkstatus Attempting to download pcmcia-cs-${BKPCMCIATOBUILD}.tar.gz
#        bkstatus from pub/pcmcia
#
#        cd ${BKSOURCEDIR}
#        #Remember that only tabs are stripped from the beginning of 
#        #"here document" lines.
#        ftp -n <<-EOTEXT
#		open hyper.stanford.edu
#		user anonymous ${USER}@${HOSTNAME}
#		cd pub/pmcia
#		binary
#		hash
#		prompt
#		lcd ${BKSOURCEDIR}
#		get linux-${BKPCMCIATOBUILD}.tar.gz
#		close
#		quit
#	EOTEXT
#
#        if [ -f ${BKSOURCEDIR}pcmcia-cs-${BKPCMCIATOBUILD}.tar.gz ]; then
#            bkstatus ${BKSOURCEDIR}pcmcia-cs-${BKPCMCIATOBUILD}.tar.gz
#            bkstatus Successfully downloaded.
#        else
#            bkwarn ${BKSOURCEDIR}pcmcia-cs-${BKPCMCIATOBUILD}.tar.gz
#            bkwarn was not successfully downloaded.
#            bkwarn Is your Internet connection down?
#            bkwarn Out of disk space?
#            bkwarn hyper.stanford.edu overloaded?
#            exit
#        fi


#FIXME check BKOPENFRESH
#-----------------------------------------------------------------------
        bkheader Opening pcmcia-cs-${BKPCMCIATOBUILD}
#-----------------------------------------------------------------------
        cd /usr/src
        ${BKLOAD} tar -xpzf ${BKSOURCEDIR}pcmcia-cs-${BKPCMCIATOBUILD}.tar.gz  2>&1 | tee -a /tmp/BKlog

        if [ ! -f /usr/src/pcmcia-cs-${BKPCMCIATOBUILD}/Makefile ]; then
            bkwarn Hmmm... there does not seem to be a Makefile in
            bkwarn /usr/src/pcmcia-cs-${BKPCMCIATOBUILD}/.  That would seem to 
            bkwarn indicate that the source files are incomplete or 
            bkwarn missing.  Please check on this and run 
            bkwarn ${BKORIGPARAMS} again.
#FIXME onetime: set BKOPENFRESH=YES, tell user
            exit
        fi

#-----------------------------------------------------------------------
        bkheader Restoring and setting configuration
#-----------------------------------------------------------------------
        cd /usr/src
        if [ -f configs/config.mk.${BKPCMCIATOBUILD} ]; then
            bkstatus Restoring config.mk
            cp configs/config.mk.${BKPCMCIATOBUILD} pcmcia-cs-${BKPCMCIATOBUILD}/config.mk  2>&1 | tee -a /tmp/BKlog
        else
            bkstatus No config.mk to restore, no problem.
        fi
        if [ -f configs/config.out.${BKPCMCIATOBUILD} ]; then
            bkstatus Restoring config.out
            cp configs/config.out.${BKPCMCIATOBUILD} pcmcia-cs-${BKPCMCIATOBUILD}/config.out  2>&1 | tee -a /tmp/BKlog
        else
            bkstatus No config.out to restore, no problem.
        fi
        cd /usr/src/pcmcia-cs-${BKPCMCIATOBUILD}
        if [ "${BKINTERACTIVE}" = "YES" ]; then
            bkstatus When asked 
            bkstatus How would you like to set kernel-specific options?
            bkstatus please answer 
            bkstatus Read from the Linux source tree.
            make config
        fi

        cd /usr/src/pcmcia-cs-${BKPCMCIATOBUILD}
        if [ -f config.mk ]; then
            cp -b -f config.mk ../configs/config.mk.${BKPCMCIATOBUILD}  2>&1 | tee -a /tmp/BKlog
        fi
        if [ -f config.out ]; then
            cp -b -f config.out ../configs/config.out.${BKPCMCIATOBUILD}  2>&1 | tee -a /tmp/BKlog
        fi



#-----------------------------------------------------------------------
        bkheader Building PCMCIA modules
#-----------------------------------------------------------------------
        cd /usr/src/pcmcia-cs-${BKPCMCIATOBUILD}
        BKTIMEBASE=${SECONDS}
        ${BKLOAD} make all MAKE="make -j ${BKNUMBUILDS}"  2>&1 | tee -a /tmp/BKlog
        bkstatus Compiling the pcmcia-cs package took $[${SECONDS}-${BKTIMEBASE}] seconds.
        make install  2>&1 | tee -a /tmp/BKlog
    else
        bkwarn ${BKSOURCEDIR}pcmcia-cs-${BKPCMCIATOBUILD}.tar.gz not found.
        bkwarn Not installing Pcmcia drivers.
    fi
fi


#FIXME move up into above section?
if [ "${BKMAKECLEANAFTER}" = "YES" ]; then 
    if [ -d /usr/src/pcmcia-cs-${BKPCMCIATOBUILD} ]; then
        #-----------------------------------------------------------------------
        bkheader Cleaning out pcmcia-cs build files.
        #-----------------------------------------------------------------------
        cd /usr/src/pcmcia-cs-${BKPCMCIATOBUILD}
        ${BKLOAD} make clean  2>&1 | tee -a /tmp/BKlog
    else
        bkstatus no /usr/src/pcmcia-cs-${BKPCMCIATOBUILD} to clean out
    fi
else
    bkstatus Current configuration chooses to not make clean.
fi



#FIXME should we run depmod at all?  It always seems to barf "unresolved 
#dependencies.
cd /usr/src

eval `cat /usr/src/linux-${BKKERNELTOBUILD}/.config | \
 grep 'CONFIG_MODULES' | tr a-z A-Z`
if [ "${CONFIG_MODULES}" = "Y" ]; then
#-----------------------------------------------------------------------
    bkheader Checking module dependencies
#-----------------------------------------------------------------------
    depmod -a ${BKKERNELTOBUILD}  2>&1 | tee -a /tmp/BKlog
    bkstatus If you had modules for this kernel version on the
    bkstatus system before this build, do not be too concerned 
    bkstatus if Unresolved Dependencies showed up just above.
    bkstatus If your system does not run 
    bkstatus depmod -a
    bkstatus at boot, it may be necessary to run this once 
    bkstatus when you reboot into the new kernel.
else
    bkstatus No modules, no dependencies to check
fi



#-----------------------------------------------------------------------
bkheader Cleanup...
#-----------------------------------------------------------------------
cd /usr/src
BKBUILDCOUNT=$[${BKBUILDCOUNT}+1]


if [ -f ~/.bkrc.tmp ] ; then
    #This rm uses a (semi) complete path, so we don't need to check pwd.
    rm -f ~/.bkrc.tmp
fi

bksplitversion ${BKKERNELTOBUILD}
case ${VERSION}.${PATCHLEVEL} in
1.0)
    BKLASTBUILT10=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT10' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT10' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
1.1)
    BKLASTBUILT11=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT11' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT11' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
1.2)
    BKLASTBUILT12=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT12' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT12' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
1.3)
    BKLASTBUILT13=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT13' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT13' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
2.0)
    BKLASTBUILT20=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT20' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT20' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
2.1)
    BKLASTBUILT21=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT21' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT21' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
2.2)
    BKLASTBUILT22=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT22' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT22' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
2.3)
    BKLASTBUILT23=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT23' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT23' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
2.4)
    BKLASTBUILT24=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT24' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT24' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
2.5)
    BKLASTBUILT25=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT25' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT25' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
2.6)
    BKLASTBUILT26=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT26' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT26' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
2.7)
    BKLASTBUILT27=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT27' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT27' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
3.0)
    BKLASTBUILT30=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT30' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT30' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
3.1)
    BKLASTBUILT31=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT31' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT31' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
3.2)
    BKLASTBUILT32=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT32' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT32' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
3.3)
    BKLASTBUILT33=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT33' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT33' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
4.0)
    BKLASTBUILT40=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT40' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT40' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
4.1)
    BKLASTBUILT41=${BKKERNELTOBUILD}
    cat ~/.bkrc | grep -v -E '^BKBUILDCOUNT|^BKLASTBUILT41' >~/.bkrc.tmp
    set | grep -E '^BKBUILDCOUNT|^BKLASTBUILT41' >>~/.bkrc.tmp
    cat ~/.bkrc.tmp >~/.bkrc ; rm -f ~/.bkrc.tmp
    ;;
*)
    bkwarn I am not aware of the kernel series ${VERSION}.${PATCHLEVEL}
    bkwarn Please get a new version of the buildkernel script at 
    bkwarn http://www.pobox.com/~wstearns
    ;;
esac


bkstatus All done with kernel build number ${BKBUILDCOUNT} 
bkstatus with ${0}!

#These rm's use complete paths, so we don't need to check pwd.
rm -f /tmp/BKfingerkernel  2>&1 | tee -a /tmp/BKlog
rm -f /tmp/BKrpmqa  2>&1 | tee -a /tmp/BKlog

cp -b -f /tmp/BKlog /usr/src/configs/bklog.${BKKERNELTOBUILD}
if [ "${BKLOGFILE}" = "/tmp/BKlog" ]; then
    bkstatus The build log can be found at /tmp/BKlog
    bkstatus and at /usr/src/configs/bklog.${BKKERNELTOBUILD}
else
    bkstatus The build log can be found at ${BKLOGFILE}
    bkstatus and at /usr/src/configs/bklog.${BKKERNELTOBUILD}
    mv -bf /tmp/BKlog ${BKLOGFILE}
fi
# Do not use bkstatus, bkwarn or bkheader after this point.  The log file 
# has already been moved or copied.  If you need to pass anything to the 
# user, use "echo ..." instead.

#User option variables
unset BKAUTOGET
unset BKBUILDTYPE
unset BKCOPYTOFLOPPY
unset BKDEBUG
unset BKINTERACTIVE
unset BKKERNELTOBUILD
unset BKPCMCIATOBUILD
unset BKLOAD
unset BKLOGFILE
unset BKMAKECLEANBEFORE
unset BKMAKECLEANAFTER
unset BKMAKETYPE
unset BKNUMBUILDS
unset BKOPENFRESH
unset BKROOTDEVICE
unset BKSOURCEDIR
unset BKVERBOSE
unset BKVIDMODE

#Internal variables
unset BKCHECKLINK
unset BKCHECKPATCH
unset BKFREESPACE
unset BKIMAGEVER
unset BKJUNK
unset BKKERNELTYPE
unset BKLASTBUILT
unset BKLEGALVER
unset BKNEWVER
unset BKORIGPARAMS
unset BKPATCH
unset BKPATCHESAPPLIED
unset BKSCRIPTVER
unset BKTIMEBASE
unset BKUNIQUEIMAGE

#Internal variables that should have been cleared right after use, but 
#just in case...
#FIXME Move some more of the above down here.
unset BKARCHI
unset BKLILOIMAGES
unset BKMAKEDIR
unset BKSHOWHELP
unset BKSHOWVER
unset BKTRYEDITOR
unset BKVALUE


#Persistent internal variables, stored in ~/.bkrc
unset BKBUILDCOUNT
unset BKLASTBUILT10
unset BKLASTBUILT11
unset BKLASTBUILT12
unset BKLASTBUILT13
unset BKLASTBUILT20
unset BKLASTBUILT21
unset BKLASTBUILT22
unset BKLASTBUILT23
unset BKLASTBUILT24
unset BKLASTBUILT25
unset BKLASTBUILT26
unset BKLASTBUILT27
unset BKLASTBUILT30
unset BKLASTBUILT31
unset BKLASTBUILT32
unset BKLASTBUILT33
unset BKLASTBUILT40
unset BKLASTBUILT41


#System variables
# Do not unset EDITOR, HOSTNAME, HOSTTYPE, or USER; I believe they are 
# created by the OS

# Kernel source tree variables, internal
unset CONFIG_MODULES
unset PATCHLEVEL
unset SUBLEVEL
unset VERSION

if [ ! "`set | grep -E '^BK' | wc -l | sed -e s/\ //g`" = "0" ]; then
    echo XXXXXXXXXX The following variables were not correctly cleaned up.  
    echo XXXXXXXXXX Only a cosmetic problem...
    echo -----------------------------
    set | grep -E '^BK'
    echo -----------------------------
fi
