#!/bin/sh
# /usr/sbin/dphys-kernel-packages - compile optimised custom kernel packages
# author Neil Franklin, last modification 2006.10.27
# copyright ETH Zuerich Physics Departement,
#   use under either modified/non-advertising BSD or GPL license


### ------ configuration for this site

# first CONF_*  various site or user dependant user config variables
# then  DEBUG_* various debugging settings
# last  SYS_*   various system internal values
# some of these are overridable by command line options


# --- CONF_* various site or subnet dependant user config variables

# where we put all the stuff needed for compiling
CONF_SOURCEDIR=.

# where we put all the stuff we have produced
CONF_TARGETDIR="${CONF_SOURCEDIR}"

# what name tag we want to distinguish kernel revisions
#   set to something like -dphys, -2-dphys, -install, ...
CONF_NAMETAG=""

# what combinations of <processor>(-smp)-<memorysize> we want to produce
CONF_VARIANTS="p1-1gb"

# this is used for debian/control Maintainer: and debian/changelog remarks
CONF_MAINT_NAME="dphys-kernel-packages"
CONF_MAINT_EMAIL="root@localhost"

# this is used for all copyright remarks in file headers
#   the second line (without "CONF_COPY=") is the second line of the string
#     needs to be done exactly so (no \) for multi-line text in an variable
CONF_COPY="released into the Public Domain, no license restrictions
  use it for what you want to, share and enjoy"


# --- DEBUG_*, various debugging settings

# set this to sleep after displaying each steps header
#DEBUG_SLEEP=yes

# set this to output debug state info after each step
#DEBUG_PRINT_STEP=yes

# set this to wait after each debug state info
#DEBUG_WAIT_STEP=yes

# set this to have an copy of the generated config files
#DEBUG_DUMP_CONFIG=yes

# set this to output .config diff relative to base config
#DEBUG_PRINT_DIFF=yes

# set this to not delete temporary files (workdir) at end
#DEBUG_LEAVE_TEMPFILES=yes


# --- SYS_*, various system internal values

# where we will generate kernels and packages
SYS_WORKDIR=/var/tmp/dphys-kernel-packages-$$-work

# in case someone wants to use/generate initrd, just uncomment this
#SYS_USEINITRD=--initrd

# in case someone wants more than just kernel_image .deb extend this
#   possible additions are: kernel_doc, kernel_headers and kernel_source
#   see  man make-kpkg  for details what these do
SYS_K_TARGETS="kernel_image kernel_source kernel_headers"
# in case someone wants more than just module binary .debs extend this
#   possible additions are: modules
SYS_M_TARGETS=modules_image


### ------ actual implementation from here on
# no user settings any more below this point

set -e


# --- get ready to work

# sanitise this place, else some commands may fail
#   must be before any commands are executed, incl config/input processing
PATH=/sbin:/bin:/usr/sbin:/usr/bin
export PATH


# --- tidy up some commands, make systematic

# stuff that goes wrong, not expected by user, not in data output, use >&2
#   so also with $0 in case this script was called by an other script
# something within the system that user does not expect, give up
CMD_FATAL="echo $0: FATAL:"
# something from users input, user will correct this and continue
CMD_ERROR="echo $0: ERROR:"
# something we can continue with, but may be wrong, and user may not suspect it
CMD_WARNING="echo $0: WARNING:"
# something most likely not wrong, but tell user for the odd case it is wrong
CMD_NOTE="echo $0: NOTE:"

# normal stuff users expect, so to stdout as normal output, no $0, no marking
CMD_INFO="echo"
# stuff users asked for, so add to stdout as normal output, no $0, but mark it
CMD_DEBUG="echo DEBUG:"

# other stuff we may want to use
CMD_SLEEP="sleep 2"
CMD_WAIT="read -p ---DEBUG-wait-after-step--- dummy"


# DEBUG_* or option controllable stuff
CMD_INFO_PRINT="${CMD_INFO}"
CMD_VERBOSE_PRINT=true
CMD_DEBUG_SLEEP=true
CMD_DEBUG_PRINT=true
CMD_DEBUG_WAIT=true

# set debug option controllable stuff here
if [ "${DEBUG_SLEEP}" = yes ] ; then
  CMD_DEBUG_SLEEP="${CMD_SLEEP}"
fi
if [ "${DEBUG_PRINT_STEP}" = yes ] ; then
  CMD_DEBUG_PRINT="${CMD_DEBUG}"
fi
if [ "${DEBUG_WAIT_STEP}" = yes ] ; then
  CMD_DEBUG_WAIT="${CMD_WAIT}"
fi


# --- config file stuff

# what we are, program and package name
NAME=dphys-kernel-packages
PNAME=dphys-kernel-packages

# check user config file(s), let user override settings
#   same config files used in makelocalsite
if [ -e /etc/"${PNAME}" ] ; then
  . /etc/"${PNAME}"
fi
if [ -e ~/."${PNAME}" ] ; then
  . ~/."${PNAME}"
fi
if [ -f ./"${PNAME}" ] ; then
  # prevent recursive calls if the program file itsself is in current directory
  if ! grep -q '+d-k-p+recurs+test+' ./"${PNAME}" ; then
    . ./"${PNAME}"
  fi
fi


# --- parse command line

# so long next parameter is a set of options (= begins with an - character)
while [ "`echo "$1" | cut -c 1`" = - ] ; do

  # extract options from parameter (cut off the "-")
  OPTS="`echo "$1" | cut -c 2-`"
  shift 1

  # so long still unprocessed option characters
  while [ "${OPTS}" != "" ] ; do

    # first option to process
    OPT="`echo "${OPTS}" | cut -c 1`"
    # and rest of options for later
    OPTS="`echo "${OPTS}" | cut -c 2-`"

    case "${OPT}" in

      s)
        # sourcedir: find all files to use in this subdirectory
        CONF_SOURCEDIR="$1"
        shift 1
        ;;

      k)
        # kernel: use this kernel archive
        KERNEL="$1"
        shift 1
        ;;

      c)
        # config: use this config file
        CONFIG="$1"
        shift 1
        ;;

      m)
        # modulesdir: use this directory full of modules
        MODULESDIR="$1"
        shift 1
        ;;

      t)
        # targetdir: place all the files produced in this directory
        CONF_TARGETDIR="$1"
        shift 1
        ;;

      q)
        # quiet: don't inform user what we are doing
        CMD_INFO_PRINT=true
        INDEXER_OPTIONS="${INDEXER_OPTIONS} -q"
        ;;

      v)
        # verbose: detailed inform user what we are doing
        CMD_VERBOSE_PRINT="${CMD_INFO}"
        ;;

      D)
        # Debug: set an debug option to yes
        eval "DEBUG_$1"=yes
        if [ "DEBUG_$1" = DEBUG_SLEEP ] ; then
          CMD_DEBUG_SLEEP="${CMD_SLEEP}"
        fi
        if [ "DEBUG_$1" = DEBUG_PRINT_STEP ] ; then
          CMD_DEBUG_PRINT="${CMD_DEBUG}"
        fi
        if [ "DEBUG_$1" = DEBUG_WAIT_STEP ] ; then
          CMD_DEBUG_WAIT="${CMD_WAIT}"
        fi
        INDEXER_OPTIONS="${INDEXER_OPTIONS} -D $1"
        shift 1
        ;;

      h)
        # help: give out help how this script can be used
        cat << END-HELP-TEXT
Usage is: $0 [options]

options:
  -s sourcedir    sourcedir: use kernel/config/modules/scripts from here
  -k kernel       kernel: use this kernel archive
  -c config       config: use this config file
  -m modulesdir   modulesdir: use this directory full of modules
  -t targetdir    targetdir: place all the files produced in this directory

  -q              quiet: don't give user an running report of what we are doing
  -v              verbose: give user detailed running report
  -D              Debug: activate an debug option, see source for operation
  -h              help: output this text, and then abort operation
END-HELP-TEXT
        exit 0
        ;;

      *)
        # not one of our recognized options
        ${CMD_ERROR} "unknown option: ${OPT}" >&2
        ${CMD_INFO} >&2
        # call self with -h to display help
        "$0" -h >&2
        exit 1
        ;;

    esac

  done

done

${CMD_DEBUG_PRINT} "options parsed"
${CMD_DEBUG_WAIT}


# --- check for stuff we need to run

# dh_testdir just used as an exemplaric debhelper command
for COMMAND in fakeroot make-kpkg make dh_testdir ; do
  if ! which "${COMMAND}" > /dev/null ; then
    ${CMD_FATAL} "failed to find ${COMMAND}, can not work, aborting ..." >&2
    ${CMD_LOG_FATAL} "failed to find ${COMMAND}, can not work, aborting ..."
    exit 1
  fi
done


# --- finding input files

${CMD_VERBOSE_PRINT} "looking for input files ..."
${CMD_DEBUG_SLEEP}

# finding stuff to use, what kernel, unless set by options
if [ "${KERNEL}" = "" ] ; then
  # last numbered (and hopefully newest) kernel
  #   complicated ls stuff is used because we need each file on separate line
  #   ls -U is used as only sorted later, after extensions are removed
  #     so that "-" for -*.tar.* does not end up before "." for .tar.*
  #     then re-add extension for full file name
  KERNEL="`ls -1U "${CONF_SOURCEDIR}"/linux-*.tar.bz2 2> /dev/null | \
      rev | cut -f 3- -d '.' | rev | sort | tail -n 1`.tar.bz2"
fi
if [ "${KERNEL}" = .tar.bz2 ] ; then
  # only an empty ending, no .tar.bz2 archive, retry for .tar.gz archive
  KERNEL="`ls -1U "${CONF_SOURCEDIR}"/linux-*.tar.gz 2> /dev/null | \
      rev | cut -f 3- -d '.' | rev | sort | tail -n 1`.tar.gz"
fi
if [ "${KERNEL}" = .tar.gz ] ; then
  ${CMD_ERROR} "no kernel archive found in ${CONF_SOURCEDIR}, aborting ..." >&2
  exit 1
fi
if [ ! -f "${KERNEL}" ] ; then
  ${CMD_ERROR} "invalid kernel file name ${KERNEL}, aborting ..." >&2
  exit 1
fi
${CMD_VERBOSE_PRINT} "using kernel: `basename "${KERNEL}"`"

# and with what config, unless set by options
if [ "${CONFIG}" = "" ] ; then
  CONFIG="`ls -1 "${CONF_SOURCEDIR}"/config* 2> /dev/null | tail -n 1`"
fi
if [ "${CONFIG}" = "" ] ; then
  ${CMD_ERROR} "no kernel config found in ${CONF_SOURCEDIR}, aborting ..." >&2
  exit 1
fi
if [ ! -f "${CONFIG}" ] ; then
  ${CMD_ERROR} "invalid config file name ${CONFIG}, aborting ..." >&2
  exit 1
fi
${CMD_VERBOSE_PRINT} "using config: `basename "${CONFIG}"`"

# and with what modules, unless set by options
if [ "${MODULESDIR}" = "" ] ; then
  if [ -d "${CONF_SOURCEDIR}/modules" ] ; then
    MODULESDIR="${CONF_SOURCEDIR}/modules"
  fi
fi
if [ "${MODULESDIR}" != "" ] ; then
  if [ ! -d "${MODULESDIR}" ] ; then
    ${CMD_ERROR} "invalid module dir name ${MODULESDIR}, aborting ..." >&2
    exit 1
  fi
  ${CMD_VERBOSE_PRINT} "using modules: `basename "${MODULESDIR}"`"
fi

${CMD_DEBUG_PRINT} "`ls -al "${KERNEL}" 2> /dev/null`"
${CMD_DEBUG_PRINT} "`ls -al "${CONFIG}" 2> /dev/null`"
if [ "${MODULESDIR}" != "" ] ; then
  ${CMD_DEBUG_PRINT} "`ls -ald "${MODULESDIR}" 2> /dev/null`"
else
  ${CMD_DEBUG_PRINT} "+++ no module directory +++"
fi
${CMD_DEBUG_WAIT}


# --- determine kernel version

${CMD_VERBOSE_PRINT} "determining kernel version ..."
${CMD_DEBUG_SLEEP}

KFILE="`basename "${KERNEL}"`"

# KRELEASE may have trailing .stuff, but that will disappear later
#   just use  -f 2 to prevent KSUBL having trailing -stuff
KRELEASE="`echo "${KFILE}"    | cut -f 2 -d '-'`"

KVERSION="`echo "${KRELEASE}" | cut -f 1 -d '.'`"
KPATCHL="`echo "${KRELEASE}"  | cut -f 2 -d '.'`"
KSUBL="`echo "${KRELEASE}"    | cut -f 3 -d '.'`"

# 2.4 or 2.6 are presently supported
KTYPE="${KVERSION}.${KPATCHL}"
if [ "${KTYPE}" != 2.4 -a "${KTYPE}" != 2.6 ] ; then
  ${CMD_FATAL} "Kernel family ${KTYPE} not recognized, can not process it," \
    "aborting ..." >&2
fi

${CMD_DEBUG_PRINT} "KRELEASE=${KRELEASE} KVERSION=${KVERSION}" \
    "KPATCHL=${KPATCHL} KSUBL=${KSUBL} KTYPE=${KTYPE}"
${CMD_DEBUG_WAIT}


# --- enumerating the wanted types of kernel

${CMD_VERBOSE_PRINT} "generating individual kernels ..."
${CMD_DEBUG_SLEEP}

# no "${CONF_VARIANTS}" in for, else intervening spaces end up in VARIANT
#   and that would then really confuse the stuff processing ${VARIANT}
# sanitise variant list, only valid chars, avoid escaping bugs hitting "for"
#   other user error splitting junk will get caught by ${VARIANT} syntax check
for VARIANT in `echo "${CONF_VARIANTS}" | tr -c -d 'a-z0-9- '` ; do


# --- working on the next specific kernel

  ${CMD_VERBOSE_PRINT} "determining variant we are next working on ..."
  ${CMD_DEBUG_SLEEP}

  # extract from format: <processor>(-smp)-<memorysize>
  if ! echo "${VARIANT}" | grep -q '-' ; then
    ${CMD_ERROR} "Variant identifier ${VARIANT} is malformed," \
        "no \"-\" in it, aborting ..." >&2
  fi

  # first <processor>: what processor options to set
  PROCESSOR="`echo "${VARIANT}" | cut -f 1 -d '-'`"

  # then smp or <memorysize>: if flag is used to set the SMP options
  #   else use this field to set up memory size
  MEMORY="`echo "${VARIANT}" | cut -f 2 -d '-'`"
  if [ "${MEMORY}" = smp ] ; then
    # is SMP, so get memory from 3rd field
    SMP=y
    MEMORY="`echo "${VARIANT}" | cut -f 3 -d '-'`"
  else
   SMP=n
  fi

  if [ "${MEMORY}" = "" ] ; then
    # there was nothing after the - in the variant specifier
    ${CMD_WARNING} "variant ${VARIANT} has no memory size specified," \
        "using 1gb ..." >&2
    MEMORY=1gb
  fi

  ${CMD_INFO_PRINT} "making kernel for variant ${VARIANT}" \
      "(processor ${PROCESSOR}" \
      `if [ "${SMP}" = y ] ; then echo "with SMP and" ; fi` \
      "with ${MEMORY} memory)" ...
  ${CMD_DEBUG_SLEEP}

  ${CMD_DEBUG_PRINT} "PROCESSOR=${PROCESSOR} SMP=${SMP} MEMORY=${MEMORY}"
  ${CMD_DEBUG_WAIT}


# --- unpacking kernel

  ${CMD_VERBOSE_PRINT} "unpacking kernel ..."
  ${CMD_DEBUG_SLEEP}

  # generate directories we will be working in
  VARWORKDIR="${SYS_WORKDIR}/${VARIANT}"
  mkdir -p "${VARWORKDIR}"

  # unpacking the kernel
  if [ "`echo "${KERNEL}" | rev | cut -f 1-2 -d '.' | rev`" = tar.bz2 ] ; then
    tar -jxpf "${KERNEL}" -C "${VARWORKDIR}"
  elif [ "`echo "${KERNEL}" | rev | cut -f 1-2 -d '.' | rev`" = tar.gz ] ; then
    tar -zxpf "${KERNEL}" -C "${VARWORKDIR}"
  else
    ${CMD_FATAL} "unknown '*.tar.*' file type for ${KERNEL}" >&2
    exit 1
  fi
  if [ -d "${VARWORKDIR}"/linux-* ] ; then
    VARKERNEL="`ls -1d "${VARWORKDIR}"/linux-* 2> /dev/null`"
    ( cd "${VARWORKDIR}" ; ln -s "${VARKERNEL}" linux )
  else
    ${CMD_FATAL} "kernel archive ${KERNEL} did not unpack" >&2
    exit 1
  fi

  ${CMD_DEBUG_PRINT} "`ls -ald "${VARKERNEL}"`"
  ${CMD_DEBUG_PRINT} "`ls -ald "${VARWORKDIR}/linux"`"
  ${CMD_DEBUG_WAIT}


# --- inserting base config

  ${CMD_VERBOSE_PRINT} "inserting base config ..."
  ${CMD_DEBUG_SLEEP}

  # inserting base config
  VARCONFIG="${VARKERNEL}/.config"
  cp -p "${CONFIG}" "${VARCONFIG}"

  ${CMD_DEBUG_PRINT} "`ls -al  "${VARCONFIG}"`"
  ${CMD_DEBUG_WAIT}


# --- fixing up config

  ${CMD_VERBOSE_PRINT} "fixing up config ..."
  ${CMD_DEBUG_SLEEP}

  # - processor stuff
  # eliminate base configs generic P1 (M586) processor and its specialities
  # insert proper processor and its specialities

  if [ "${PROCESSOR}" = p3 -a "${KTYPE}" = 2.4 ] ; then
    sed -e '/CONFIG_M586=y/s//# CONFIG_M586 is not set/' \
        -e '/# CONFIG_MPENTIUMIII is not set/s//CONFIG_MPENTIUMIII=y/' \
        -e '/CONFIG_X86_USE_STRING_486=y/d' \
        -e '/CONFIG_X86_ALIGNMENT_16=y/d' \
        -e '/CONFIG_X86_PPRO_FENCE=y/d' \
        -e '/# CONFIG_X86_F00F_WORKS_OK is not set/s//CONFIG_X86_GOOD_APIC=y\
CONFIG_X86_PGE=y\
CONFIG_X86_USE_PPRO_CHECKSUM=y\
CONFIG_X86_F00F_WORKS_OK=y/' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${PROCESSOR}" = p4 -a "${KTYPE}" = 2.4 ] ; then
    sed -e '/CONFIG_M586=y/s//# CONFIG_M586 is not set/' \
        -e '/# CONFIG_MPENTIUM4 is not set/s//CONFIG_MPENTIUM4=y/' \
        -e '/CONFIG_X86_L1_CACHE_SHIFT=5/s//CONFIG_X86_L1_CACHE_SHIFT=7/' \
        -e '/CONFIG_X86_USE_STRING_486=y/d' \
        -e '/CONFIG_X86_ALIGNMENT_16=y/d' \
        -e '/CONFIG_X86_PPRO_FENCE=y/d' \
        -e '/# CONFIG_X86_F00F_WORKS_OK is not set/s//CONFIG_X86_GOOD_APIC=y\
CONFIG_X86_PGE=y\
CONFIG_X86_USE_PPRO_CHECKSUM=y\
CONFIG_X86_F00F_WORKS_OK=y/' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${PROCESSOR}" = k7 -a "${KTYPE}" = 2.4 ] ; then
    sed -e '/CONFIG_M586=y/s//# CONFIG_M586 is not set/' \
        -e '/# CONFIG_MK7 is not set/s//CONFIG_MK7=y/' \
        -e '/CONFIG_X86_L1_CACHE_SHIFT=5/s//CONFIG_X86_L1_CACHE_SHIFT=6/' \
        -e '/CONFIG_X86_USE_STRING_486=y/d' \
        -e '/CONFIG_X86_ALIGNMENT_16=y/d' \
        -e '/CONFIG_X86_PPRO_FENCE=y/d' \
        -e '/# CONFIG_X86_F00F_WORKS_OK is not set/s//CONFIG_X86_GOOD_APIC=y\
CONFIG_X86_USE_3DNOW=y\
CONFIG_X86_PGE=y\
CONFIG_X86_USE_PPRO_CHECKSUM=y\
CONFIG_X86_F00F_WORKS_OK=y/' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${PROCESSOR}" = k8 -a "${KTYPE}" = 2.4 ] ; then
    # actually  make menconfig  produces CONFIG_MK7 for k8, so rest not tested
    #   assume just drop CONFIG_X86_USE_3DNOW as in 2.6
    sed -e '/CONFIG_M586=y/s//# CONFIG_M586 is not set/' \
        -e '/# CONFIG_MK8 is not set/s//CONFIG_MK8=y/' \
        -e '/CONFIG_X86_L1_CACHE_SHIFT=5/s//CONFIG_X86_L1_CACHE_SHIFT=6/' \
        -e '/CONFIG_X86_USE_STRING_486=y/d' \
        -e '/CONFIG_X86_ALIGNMENT_16=y/d' \
        -e '/CONFIG_X86_PPRO_FENCE=y/d' \
        -e '/# CONFIG_X86_F00F_WORKS_OK is not set/s//CONFIG_X86_GOOD_APIC=y\
CONFIG_X86_PGE=y\
CONFIG_X86_USE_PPRO_CHECKSUM=y\
CONFIG_X86_F00F_WORKS_OK=y/' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${PROCESSOR}" = p3 -a "${KTYPE}" = 2.6 ] ; then
    sed -e '/CONFIG_M586=y/s//# CONFIG_M586 is not set/' \
        -e '/# CONFIG_MPENTIUMIII is not set/s//CONFIG_MPENTIUMIII=y/' \
        -e '/CONFIG_X86_PPRO_FENCE=y/d' \
        -e '/CONFIG_X86_F00F_BUG=y/d' \
        -e '/CONFIG_X86_ALIGNMENT_16=y/s//CONFIG_X86_GOOD_APIC=y\
CONFIG_X86_INTEL_USERCOPY=y\
CONFIG_X86_USE_PPRO_CHECKSUM=y\
CONFIG_X86_TSC=y/' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${PROCESSOR}" = p4 -a "${KTYPE}" = 2.6 ] ; then
    sed -e '/CONFIG_M586=y/s//# CONFIG_M586 is not set/' \
        -e '/# CONFIG_MPENTIUM4 is not set/s//CONFIG_MPENTIUM4=y/' \
        -e '/CONFIG_X86_L1_CACHE_SHIFT=5/s//CONFIG_X86_L1_CACHE_SHIFT=7/' \
        -e '/CONFIG_X86_PPRO_FENCE=y/d' \
        -e '/CONFIG_X86_F00F_BUG=y/d' \
        -e '/CONFIG_X86_ALIGNMENT_16=y/s//CONFIG_X86_GOOD_APIC=y\
CONFIG_X86_INTEL_USERCOPY=y\
CONFIG_X86_USE_PPRO_CHECKSUM=y\
CONFIG_X86_TSC=y/' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${PROCESSOR}" = k7 -a "${KTYPE}" = 2.6 ] ; then
    sed -e '/CONFIG_M586=y/s//# CONFIG_M586 is not set/' \
        -e '/# CONFIG_MK7 is not set/s//CONFIG_MK7=y/' \
        -e '/CONFIG_X86_L1_CACHE_SHIFT=5/s//CONFIG_X86_L1_CACHE_SHIFT=6/' \
        -e '/CONFIG_X86_PPRO_FENCE=y/d' \
        -e '/CONFIG_X86_F00F_BUG=y/d' \
        -e '/CONFIG_X86_ALIGNMENT_16=y/s//CONFIG_X86_GOOD_APIC=y\
CONFIG_X86_INTEL_USERCOPY=y\
CONFIG_X86_USE_PPRO_CHECKSUM=y\
CONFIG_X86_USE_3DNOW=y\
CONFIG_X86_TSC=y/' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${PROCESSOR}" = k8 -a "${KTYPE}" = 2.6 ] ; then
    sed -e '/CONFIG_M586=y/s//# CONFIG_M586 is not set/' \
        -e '/# CONFIG_MK8 is not set/s//CONFIG_MK8=y/' \
        -e '/CONFIG_X86_L1_CACHE_SHIFT=5/s//CONFIG_X86_L1_CACHE_SHIFT=6/' \
        -e '/CONFIG_X86_PPRO_FENCE=y/d' \
        -e '/CONFIG_X86_F00F_BUG=y/d' \
        -e '/CONFIG_X86_ALIGNMENT_16=y/s//CONFIG_X86_GOOD_APIC=y\
CONFIG_X86_INTEL_USERCOPY=y\
CONFIG_X86_USE_PPRO_CHECKSUM=y\
CONFIG_X86_TSC=y/' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi


  # - SMP stuff
  # just add all the SMP configs

  if [ "${SMP}" = y -a "${KTYPE}" = 2.4 ] ; then
    sed -e '/# CONFIG_SMP is not set/s//CONFIG_SMP=y\
CONFIG_NR_CPUS=32\
# CONFIG_X86_NUMA is not set/' \
        -e '/# CONFIG_X86_UP_APIC is not set/d' \
        -e '/# CONFIG_X86_UP_IOAPIC is not set/d' \
        -e '/CONFIG_X86_TSC=y/a\
CONFIG_HAVE_DEC_LOCK=y' \
        -e '/CONFIG_NET=y/a\
CONFIG_X86_IO_APIC=y\
CONFIG_X86_LOCAL_APIC=y' \
        -e '/# CONFIG_HOTPLUG_PCI_COMPAQ_NVRAM is not set/a\
# CONFIG_HOTPLUG_PCI_IBM is not set' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${SMP}" = y -a "${KTYPE}" = 2.6 ] ; then
    sed -e '/CONFIG_BROKEN_ON_SMP=y/s//CONFIG_LOCK_KERNEL=y/' \
        -e '/CONFIG_IKCONFIG_PROC=y/a\
# CONFIG_CPUSETS is not set' \
        -e '/CONFIG_KMOD=y/a\
CONFIG_STOP_MACHINE=y' \
        -e '/# CONFIG_SMP is not set/s//CONFIG_SMP=y\
CONFIG_NR_CPUS=8\
# CONFIG_SCHED_SMT is not set/' \
        -e '/CONFIG_X86_UP_APIC=y/d' \
        -e '/CONFIG_X86_UP_IOAPIC=y/s//CONFIG_PREEMPT_BKL=y/' \
        -e '/# CONFIG_EFI is not set/a\
CONFIG_IRQBALANCE=y' \
        -e '/# CONFIG_SOFTWARE_SUSPEND is not set/d' \
        -e '/# CONFIG_ACPI_SLEEP is not set/d' \
        -e '/# CONFIG_SCx200 is not set/a\
# CONFIG_HOTPLUG_CPU is not set' \
        -e '/# CONFIG_FTAPE is not set/d' \
        -e '/CONFIG_USB_SERIAL_WHITEHEAT/d' \
        -e '/CONFIG_LOG_BUF_SHIFT=14/s//CONFIG_LOG_BUF_SHIFT=15/' \
        -e '/CONFIG_GENERIC_IRQ_PROBE=y/a\
CONFIG_GENERIC_PENDING_IRQ=y\
CONFIG_X86_SMP=y\
CONFIG_X86_HT=y' \
        -e '/CONFIG_X86_BIOS_REBOOT=y/a\
CONFIG_X86_TRAMPOLINE=y' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi


  # - memory stuff
  # eliminate base configs standard memory and its specialities
  # insert proper memory size and its specialities

  if [ "${MEMORY}" = 4gb -a "${KTYPE}" = 2.4 ] ; then
    sed -e '/CONFIG_NOHIGHMEM=y/s//# CONFIG_NOHIGHMEM is not set/' \
        -e '/# CONFIG_HIGHMEM4G is not set/s//CONFIG_HIGHMEM4G=y/' \
        -e '/# CONFIG_HIGHMEM is not set/s//CONFIG_HIGHMEM=y\
# CONFIG_HIGHIO is not set/' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${MEMORY}" = 64gb -a "${KTYPE}" = 2.4 ] ; then
    sed -e '/CONFIG_NOHIGHMEM=y/s//# CONFIG_NOHIGHMEM is not set/' \
        -e '/# CONFIG_HIGHMEM64G is not set/s//CONFIG_HIGHMEM64G=y/' \
        -e '/# CONFIG_HIGHMEM is not set/s//CONFIG_HIGHMEM=y\
CONFIG_X86_PAE=y\
# CONFIG_HIGHIO is not set/' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${MEMORY}" = 4gb -a "${KTYPE}" = 2.6 ] ; then
    sed -e '/CONFIG_NOHIGHMEM=y/s//# CONFIG_NOHIGHMEM is not set/' \
        -e '/# CONFIG_HIGHMEM4G is not set/s//CONFIG_HIGHMEM4G=y/' \
        -e '/# CONFIG_HIGHMEM64G is not set/a\
CONFIG_HIGHMEM=y' \
        -e '/CONFIG_SPLIT_PTLOCK_CPUS=4/a\
# CONFIG_HIGHPTE is not set' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi

  if [ "${MEMORY}" = 64gb -a "${KTYPE}" = 2.6 ] ; then
    sed -e '/CONFIG_NOHIGHMEM=y/s//# CONFIG_NOHIGHMEM is not set/' \
        -e '/# CONFIG_HIGHMEM64G is not set/s//CONFIG_HIGHMEM64G=y\
CONFIG_HIGHMEM=y\
CONFIG_X86_PAE=y/' \
        -e '/CONFIG_SPLIT_PTLOCK_CPUS=4/a\
# CONFIG_HIGHPTE is not set' \
        "${VARCONFIG}" > "${VARCONFIG}.tmp"
    mv "${VARCONFIG}.tmp" "${VARCONFIG}"
  fi


  if [ "${DEBUG_DUMP_CONFIG}" = yes ] ; then
    ${CMD_INFO_PRINT} "dumping generated .config ..."
    cp -p "${VARCONFIG}" ".config-${VARIANT}"
  fi

  ${CMD_DEBUG_PRINT} "`ls -ald "${VARCONFIG}"`"
  if [ "${DEBUG_PRINT_DIFF}" = yes ] ; then
    # || true is needed because the strage return values from diff crash set -e
    diff "${CONFIG}" "${VARCONFIG}" || true
  fi
  ${CMD_DEBUG_WAIT}


# --- compiling kernel and packaging it

  ${CMD_VERBOSE_PRINT} "compiling kernel and packaging it ..."
  ${CMD_DEBUG_SLEEP}

  DATE_VERSION="`date +%Y%m%d.%H%M%S`"
  PKG_VERSION="${DATE_VERSION}"

  # mark package name with compile details
  APPEND_STUFF="${CONF_NAMETAG}-${VARIANT}"


  # do the actual compile and packaging, main kernel package
  ( cd "${VARWORKDIR}/linux" ; fakeroot make-kpkg clean )
  #   no "" around ${SYS_USEINITRD} and ${SYS_K_TARGETS}
  #     make-kpkg can not handle the result (empty and multipart parameters)
  ( cd "${VARWORKDIR}/linux" ; KPKG_MAINTAINER="${CONF_MAINT_NAME}" \
        KPKG_EMAIL="${CONF_MAINT_EMAIL}" \
        fakeroot make-kpkg --revision "${PKG_VERSION}" ${SYS_USEINITRD} \
        --append-to-version "${APPEND_STUFF}" ${SYS_K_TARGETS} )
  # echo is needed, else the * is not expanded
  VARKERNELDEB="`echo "${VARWORKDIR}"/kernel-image-*.deb`"
  if [ ! -f "${VARKERNELDEB}" ] ; then
    # package names changed from sarge (kernel-*) to etch (linux-*), allow both
    VARKERNELDEB="`echo "${VARWORKDIR}"/linux-image-*.deb`"
  fi
  if [ ! -f "${VARKERNELDEB}" ] ; then
    # abort before waisting time compiling modules
    ${CMD_FATAL} "failed to produce the kernel image .deb package," \
        "most likely there was an problem with the kernel compilation" \
        "process, aborting ..." >&2
    exit 1
  fi

  # kernel name and version for reboot and module names, to track updates
  VARKERNELFILE="`echo "${VARKERNELDEB}" | rev | cut -f 1 -d '/' | rev`"
  VARKERNELPKG="`echo "${VARKERNELFILE}" | cut -f 1 -d '_'`"
  VARKERNELVER="`echo "${VARKERNELPKG}"  | cut -f 3- -d '-'`"

  ${CMD_DEBUG_PRINT} "`ls -ald "${VARKERNELDEB}"`"
  ${CMD_DEBUG_PRINT} "VARKERNELFILE=${VARKERNELFILE}" \
      "VARKERNELVER=${VARKERNELVER}"
  ${CMD_DEBUG_WAIT}


# --- start reboot control package

  # needs to be before modules, because they add dependencies to this

  ${CMD_VERBOSE_PRINT} "starting reboot control package ..."
  ${CMD_DEBUG_SLEEP}

  # add kernel version after base name, to track updates
  REBOOTNAME="kernel-reboot--${VARKERNELVER}"

  # generate directory for doing this
  VARREBOOTDIR="${VARWORKDIR}/${REBOOTNAME}"
  mkdir -p "${VARREBOOTDIR}"
  # no "upstream" maintainer files, as no functionality installed
  #   entire package is for dependencies and running an postinst

  # debianise this rebooter, for compiling and packaging
  VARREBOOTDEBDIR="${VARREBOOTDIR}/debian"
  mkdir -p "${VARREBOOTDEBDIR}"

 
  # control file
  #   Depends: will be expanded by each module compiled
  cat << END-CONTROL-FILE > "${VARREBOOTDEBDIR}/control"
Source: ${REBOOTNAME}
Section: base
Priority: optional
Maintainer: ${CONF_MAINT_NAME} <${CONF_MAINT_EMAIL}>
Standards-Version: 3.6.1

Package: ${REBOOTNAME}
Depends: ${VARKERNELPKG}
Architecture: any
Description: ${VARKERNELPKG} reboot control file
 This is an auto-generated package, generated to auto-make an reboot control
 for the custom kernel ${VARKERNELPKG}
END-CONTROL-FILE


  # copyright file
  cat << END-COPYRIGHT-FILE > "${VARREBOOTDEBDIR}/copyright"
This package ${REBOOTNAME} is ${CONF_COPY}
END-COPYRIGHT-FILE


  # changelog file
  #   when packaging, debianise this version with RFC date from now
  DATE_RFC="`date -R`"
  cat << END-CHANGELOG-FILE > "${VARREBOOTDEBDIR}/changelog"
${REBOOTNAME} (${PKG_VERSION}) stable; urgency=medium

  * Auto-packaged module, recompile only for new version/source, no history

 -- ${CONF_MAINT_NAME} <${CONF_MAINT_EMAIL}>  ${DATE_RFC}
END-CHANGELOG-FILE


  # rules file
  cat << END-RULES-MAKEFILE > "${VARREBOOTDEBDIR}/rules"
#!/usr/bin/make -f
# details see makesourcepackage source, this is reduced version

PATH=/sbin:/bin:/usr/sbin:/usr/bin

# This is the debhelper compatibility version to use
export DH_COMPAT=3

build: build-stamp

build-stamp:
	@dh_testdir
	@# compiling can be done as non-root, no test here

	@# no upstream Makefile
	@# mark this after compiling
	@touch build-stamp

clean:
	@dh_testdir
	@dh_testroot

	@# clean up install run and build, I prefer this before clean upstream
	@dh_clean

	@# unmark "compile done" flag before "uncompiling"
	@rm -f build-stamp

	@# no upstream Makefile

install: build
	@dh_testdir
	@dh_testroot

	@# clean up debris from previous install runs, leave Debian files
	@dh_clean -k

	@# create our debian/<packagename> directory
	@dh_installdirs

	@# no upstream Makefile

binary-indep: build install
	@# We have nothing to do here, package of other type (arch)

binary-arch: build install
	@dh_testdir
	@dh_testroot
	@#dh_installdocs
	@dh_installchangelogs
	@dh_compress
	@dh_fixperms
	@dh_installdeb
	@dh_gencontrol
	@dh_md5sums
	@dh_builddeb

binary: binary-indep binary-arch

.PHONY: build clean binary-indep binary-arch binary install
END-RULES-MAKEFILE

  chmod 755 "${VARREBOOTDEBDIR}/rules"


  # postinst file, this is the reason for the entire package
  cat << END-POSTINST-FILE > "${VARREBOOTDEBDIR}/${REBOOTNAME}.postinst"
#!/bin/sh
# /var/lib/dpkg/info/${REBOOTNAME}.postinst
#   - shedule reboot by dphys-admin after kernel install
# author/generator ${NAME} for ${CONF_MAINT_NAME}
#   last modification/generation ${DATE_VERSION}

PATH=/sbin:/bin:/usr/sbin:/usr/bin

#DEBHELPER#

# so that dphys-admin does/shedules an clean reboot of the machine
touch /root/NEED-REBOOT

exit 0
END-POSTINST-FILE

  chmod 755 "${VARREBOOTDEBDIR}/${REBOOTNAME}.postinst"


  ${CMD_DEBUG_PRINT} "`ls -al "${VARREBOOTDEBDIR}/control"`"
  ${CMD_DEBUG_PRINT} "`ls -al "${VARREBOOTDEBDIR}/copyright"`"
  ${CMD_DEBUG_PRINT} "`ls -al "${VARREBOOTDEBDIR}/changelog"`"
  ${CMD_DEBUG_PRINT} "`ls -al "${VARREBOOTDEBDIR}/rules"`"
  ${CMD_DEBUG_PRINT} "`ls -al "${VARREBOOTDEBDIR}/${REBOOTNAME}.postinst"`"
  ${CMD_DEBUG_WAIT}


# --- handle modules

  ${CMD_VERBOSE_PRINT} "handling modules ..."
  ${CMD_DEBUG_SLEEP}

  if [ "${MODULESDIR}" != "" ] ; then

    # generate directory for unpacking modules into
    VARMODULESDIR="${VARWORKDIR}/modules"
    mkdir -p "${VARMODULESDIR}"

    for MODULE in "${MODULESDIR}"/*.tar.* ; do

      # nonsense paths get caught here
      if [ ! -f "${MODULE}" ] ; then
        ${CMD_ERROR} "Module ${MODULE} does not exist, aborting ..." >&2
      fi


# --- unpack this module

      ${CMD_VERBOSE_PRINT} "unpacking module ${MODULE} ..."
      ${CMD_DEBUG_SLEEP}

      # unpacking the module
      if [ "`echo "${MODULE}" | rev | cut -f 1-2 -d '.' | rev`" \
          = tar.bz2 ] ; then
        tar -jxpf "${MODULE}" -C "${VARMODULESDIR}"
        # where tar will have unpacked contents to
        MODULEDIR="`tar -jtf "${MODULE}" | head -n 1 | cut -f 1 -d '/'`"
      elif [ "`echo "${MODULE}" | rev | cut -f 1-2 -d '.' | rev`" = \
          tar.gz ] ; then
        tar -zxpf "${MODULE}" -C "${VARMODULESDIR}"
        MODULEDIR="`tar -ztf "${MODULE}" | head -n 1 | cut -f 1 -d '/'`"
      else
        ${CMD_FATAL} "unknown '*.tar.*' file type for ${MODULE}" >&2
        exit 1
      fi
      VARMODULEDIR="${VARMODULESDIR}/${MODULEDIR}"

      ${CMD_DEBUG_PRINT} "`ls -ald "${VARMODULEDIR}"`"
      ${CMD_DEBUG_WAIT}


# --- debianise this module

      ${CMD_VERBOSE_PRINT} "debianising module ..."
      ${CMD_DEBUG_SLEEP}

      # debianise this module, for make-kpkg compiling and packaging
      VARMODULEDEBDIR="${VARMODULEDIR}/debian"
      mkdir -p "${VARMODULEDEBDIR}"

      # name with directory and .tar.* ending removed
      MODULEFILE="`basename "${MODULE}"`"
      MODULEFILEBASE="`echo "${MODULEFILE}" | rev | cut -f 3- -d '.' | rev`"
      # above with illegal _ and A-Z chars converted to - and a-z chars
      MODULEBASE="`echo "${MODULEFILEBASE}" | tr '_' '-' | tr 'A-Z' 'a-z'`"
      # add kernel version after module name, to track updates
      MODULENAME="${MODULEBASE}--${VARKERNELVER}"


      # control file, must overwrite any existing one, else system fails
      cat << END-CONTROL-FILE > "${VARMODULEDEBDIR}/control"
Source: ${MODULENAME}
Section: base
Priority: optional
Maintainer: ${CONF_MAINT_NAME} <${CONF_MAINT_EMAIL}>
Build-Depends-Indep: kernel-headers
Standards-Version: 3.6.1

Package: ${MODULENAME}
Depends: ${VARKERNELPKG}
Architecture: any
Description: ${VARKERNELPKG} custom modules
 This is an auto-debianised package, generated to auto-make fitting modules
 for the custom kernel ${VARKERNELPKG}
END-CONTROL-FILE


      # copyright file, no technical relevance, so leave existing
      if [ ! -f "${VARMODULEDEBDIR}/copyright" ]; then

        cat << END-COPYRIGHT-FILE > "${VARMODULEDEBDIR}/copyright"
This package ${MODULENAME} is ${CONF_COPY}
END-COPYRIGHT-FILE

      fi


      # changelog file, add new record to front, save old for tagging on
      if [ -f "${VARMODULEDEBDIR}/changelog" ]; then
        mv "${VARMODULEDEBDIR}/changelog" \
            "${VARMODULEDEBDIR}/changelog.old"
      fi

      # when packaging, debianise this version with RFC date from now
      DATE_RFC="`date -R`"

      cat << END-CHANGELOG-FILE > "${VARMODULEDEBDIR}/changelog"
${MODULENAME} (${PKG_VERSION}) stable; urgency=medium

  * Auto-packaged module, recompile only for new version/source, no history

 -- ${CONF_MAINT_NAME} <${CONF_MAINT_EMAIL}>  ${DATE_RFC}
END-CHANGELOG-FILE

      # tag existing changelog on to new entry if it was saved
      if [ -f "${VARMODULEDEBDIR}/changelog.old" ] ; then
        echo >> "${VARMODULEDEBDIR}/changelog"
        cat "${VARMODULEDEBDIR}/changelog.old" >> \
            "${VARMODULEDEBDIR}/changelog"
      fi


      # rules file, must overwrite any existing one, else system fails
      cat << END-RULES-MAKEFILE > "${VARMODULEDEBDIR}/rules"
#!/usr/bin/make -f

PATH=/sbin:/bin:/usr/sbin:/usr/bin

# called by make-kpkg with following environment:
#KVERS="2.4.31-pre2" or whatever, taken from users kernel archive
#KSRC="/usr/src/linux" or whatever, taken from \${SYS_WORKDIR}/...
#KMAINT=\${KPKG_MAINTAINER}, taken from \${CONF_MAINT_NAME}
#KEMAIL=\${KPKG_EMAIL}, taken from \${CONF_MAINT_EMAIL}
#KDREV=\${PKG_VERSION}, taken from date up above

# This is the debhelper compatibility version to use
export DH_COMPAT=3

configure: configure-stamp
configure-stamp:
	@make -f debian/rules configure-module
	@touch configure-stamp

build: build-stamp
build-stamp: configure-stamp
	@make -f debian/rules build-module
	@touch build-stamp

install: install-stamp
install-stamp: build-stamp
	@make -f debian/rules \
	  DESTDIR=\$(CURDIR)/debian/\`dh_listpackages\` install-module
	@touch install-stamp

clean:
	@dh_clean
	@make -f debian/rules \
	  DESTDIR=\$(CURDIR)/debian/\`dh_listpackages\` clean-module
	@rm install-stamp build-stamp configure-stamp

binary_modules: binary-modules
binary-modules: configure-stamp build-stamp install-stamp
	@dh_testdir
	@dh_testroot
	@dh_installdirs
	@dh_installchangelogs
	@dh_installdocs
	@dh_strip
	@dh_compress
	@dh_fixperms
	@dh_installdeb
	@dh_shlibdeps
	@dh_gencontrol
	@dh_builddeb --destdir=\$(KSRC)/..

kdist_configure: configure-stamp
kdist_config: configure-stamp
kdist:
	@make -f debian/rules binary-modules
kdist_clean: clean
# make-kpkg enters here at kdist_image when doing modules-image:
kdist_image:
	@make -f debian/rules binary-modules
	@make -f debian/rules clean
END-RULES-MAKEFILE

      # ensure an empty line
      echo >> "${VARMODULEDEBDIR}/rules"

      # module specific configure/build/install/clean part for rules file
      #   expected to implement [configure|build|install|clean]-module
      # name same as .tar.[gz|bz2] with ending replaced by .rules
      RULES="${MODULESDIR}/${MODULEFILEBASE}.rules"
      if [ ! -f "${RULES}" ] ; then
        ${CMD_ERROR} "missing ${RULES} for module ${MODULE}, aborting ..." >&2
        exit 1
      fi
      cat "${RULES}" >> "${VARMODULEDEBDIR}/rules"

      chmod 755 "${VARMODULEDEBDIR}/rules"


      ${CMD_DEBUG_PRINT} "`ls -ald "${RULES}"`"
      if [ "${DEBUG_PRINT_STEP}" = yes ] ; then
        ls -al "${VARMODULEDEBDIR}" 2> /dev/null
      fi
      ${CMD_DEBUG_WAIT}


# --- add this module to reboot control packages depends

      ${CMD_VERBOSE_PRINT} "depending reboot control ..."
      ${CMD_DEBUG_SLEEP}

      # control file, expand by each module compiled
      sed -e '/^Depends: /s/$/, '"${MODULENAME}"'/' \
          "${VARREBOOTDEBDIR}/control" > "${VARREBOOTDEBDIR}/.control"
      mv "${VARREBOOTDEBDIR}/.control" "${VARREBOOTDEBDIR}/control"

      ${CMD_DEBUG_PRINT} "`ls -ald "${VARREBOOTDEBDIR}/control"`"
      ${CMD_DEBUG_WAIT}


# --- end handling this module

    done


# --- compile all modules and package them

    ${CMD_VERBOSE_PRINT} "compiling and packaging all modules ..."
    ${CMD_DEBUG_SLEEP}

    ( cd "${VARWORKDIR}/linux" ; KPKG_MAINTAINER="${CONF_MAINT_NAME}" \
          KPKG_EMAIL="${CONF_MAINT_EMAIL}" MODULE_LOC="${VARMODULESDIR}" \
          VERSION_H_OK=yes fakeroot make-kpkg \
          --append-to-version "${APPEND_STUFF}" ${SYS_M_TARGETS} )

    if [ "${DEBUG_PRINT_STEP}" = yes ] ; then
      ls -al "${VARWORKDIR}"/*.deb 2> /dev/null
    fi
    ${CMD_DEBUG_WAIT}

  fi


# --- finalise reboot control package

  ${CMD_VERBOSE_PRINT} "finalising reboot control package ..."
  ${CMD_DEBUG_SLEEP}

  # then build the actual reboot package, now that depends are in it
  ( cd "${VARREBOOTDIR}" ; dpkg-buildpackage -rfakeroot -uc -us )
  # run a test over package, to get more error messages
  ( cd "${VARWORKDIR}" ; lintian -i "${REBOOTNAME}"_*.changes )

  if [ "${DEBUG_PRINT_STEP}" = yes ] ; then
    ls -al "${VARWORKDIR}"/*.deb 2> /dev/null
  fi
  ${CMD_DEBUG_WAIT}


# --- save the produced .deb files to where user expects them

  ${CMD_VERBOSE_PRINT} "saving .deb files ..."
  ${CMD_DEBUG_SLEEP}

  # at least the kernel image .deb will exist, so no test for *.deb
  cp -p "${VARWORKDIR}"/*.deb "${CONF_TARGETDIR}"

  if [ "${DEBUG_PRINT_STEP}" = yes ] ; then
    ls -al "${CONF_TARGETDIR}"/*.deb 2> /dev/null
  fi
  ${CMD_DEBUG_WAIT}


# --- variant tidying up

  ${CMD_VERBOSE_PRINT} "tidying up variant ${VARIANT} ..."
  ${CMD_DEBUG_SLEEP}

  if [ "${DEBUG_PRINT_STEP}" = yes ] ; then
    ls -al "${VARWORKDIR}" 2> /dev/null
  fi
  ${CMD_DEBUG_WAIT}

  # remove all temporary directories and their contents, to save space
  #   must be after debug printout
  if [ "${DEBUG_LEAVE_TEMPFILES}" != yes ] ; then
    # but offer to leave them to investigate bugs
    rm -rf "${VARWORKDIR}"
  fi

done


# --- final tidying up

  ${CMD_VERBOSE_PRINT} "tidying up ..."
  ${CMD_DEBUG_SLEEP}

if [ "${DEBUG_PRINT_STEP}" = yes ] ; then
  ls -al "${SYS_WORKDIR}" 2> /dev/null
fi
${CMD_DEBUG_WAIT}

if [ "${DEBUG_LEAVE_TEMPFILES}" != yes ] ; then
  # use rmdir so that not deleted variants will raise an error
  rmdir "${SYS_WORKDIR}"
fi

exit 0
