#!/bin/bash
######################################################################
# kmp-builder
######################################################################

me=$(basename "$0")
bin=$(cd "$(dirname "$0")" && /bin/pwd)

err  () { echo 1>&2 "$*";   }
log  () { err "$me: $*";     }
vlog () { $verbose && err "$me: $*"; }
fail () { log "$*"; exit 1; }
try  () { "$@" || fail "'$*' failed"; }
trace() { log "invoking: $*"; "$@"; }
vtrace() { vlog "invoking: $*"; "$@"; }


usage() {
  err
  err "usage:"
  err "  $me [options] <dir> <tag> net <distro> <sp> <arch:kernel>"
  err
  err "options:"
  err "  --disttag <x>     -- specify disttag (only used for log file name)"
  err "  -v                -- verbose logging"
  err
  err "eg: $me /home/bob/v5 v1_1_5010 net SLES10 base i686:2.4.20-8"
  err
  exit 1
}


######################################################################
# main()

verbose=false
disttag=


# Parse the command line arguments.
while [ $# -gt 0 ]; do
  case "$1" in
    --disttag)	disttag="$2"; shift;;
    -v)		verbose=true;;
    -*)		usage;;
    *)		break;;
  esac
  shift
done

[ $# -eq 6 ] || usage
dir="$1/rpm"
shift
TAG="$1"
version="$(echo "$TAG" | sed 's/^v//; s/_/./g')"
shift
[ "x$1" = xnet ] || fail "$me: type must be 'net'"
shift
DISTRO=$1
shift
SP=$1
shift

# TODO consume kernel:arch in a while loop as per the other builders
kernel=${1##*:}
arch=${1%%:*}
shift

vlog "whoami=$(whoami)"
vlog "$(uname -a)"

# Some sanity please!
try [ -d "$dir" ]
try cd "$dir"

logd="$dir/logs"
try mkdir -p "$logd"

[ -n "$LD_PRELOAD" ] && {
  # This bit of hackery combines with hackery in the rpmbuild-master
  # scripts to make it look like we're running on a different system from
  # the one the kernel thinks we're running.  (Needed because we run this
  # script in a chroot environment).
  export "FAKEARCH_MACHINE=$arch"
  export "FAKEARCH_RELEASE=$kernel"
  
  vlog "fakearch: $(uname -a) wanted $arch"
  vlog "fakerelease: $(uname -r) wanted $kernel"
}

logf="$logd/kmp-$TAG-$disttag-$arch.log"

# KMP dependency generation leaves temporary files behind, and they
# eventually fill up the partition because chroot'd /tmp directories are
# not emptied.  Clean up these files ourselves.
find /tmp -maxdepth 1 -name 'find-requires.ksyms.*' -mmin +10 -exec rm -- {} \+

log "Generating KMPs: arch=$arch log=$(basename "$logf")"
vtrace rpmbuild -bb --define "_topdir $dir" --target=$arch $dir/SPECS/sfc-kmp.spec &> "$logf"
rc=$?

$verbose && [ -f "$logf" ] && cat "$logf"

[ $rc = 0 ] || {
  log "FAILED: $rc"
  try mkdir -p "$logd/failures"
  try mv "$logf" "$logd/failures"
}

vlog "Exiting."
exit $rc
