#!/bin/bash
# Version: 1.7 GSB Section SMBuild - Do not remove this line!
# Copyright (c) 2007, 2008:
#   Darren 'Tadgy' Austin <darren (at) gnomeslackbuild.org>, Coventry, UK.
# Licenced under the terms of the GNU General Public Licence version 3.
#
# Modified and trimmed extensively for use with SMLinux

# Prevent users from directly executing this section autobuild file. The whole build 
# process has to be initiated from the main autobuild file.
if [ -z "$SM_AUTOBUILD" ] ; then
  echo "Please invoke the main ssb.SMBuild file rather than this section build file because"
  echo "it has the required functions that are exported to this section build file during"
  echo "the build process"
  exit 1
fi

. ${BUILDVARS:-/etc/buildvars.conf}

if [ -n "$SM_AUTOBUILDTEMP" ] ; then
  SM_AUTOBUILDTEMP="$(echo $SM_AUTOBUILDTEMP)"
  export SM_AUTOBUILDTEMP
fi

SM_COLOURS=0
export SM_COLOURS

# Make sure we are in the right directory (you can never trust users..)
cd $( cd ${BASH_SOURCE%/*} ; pwd )

# Section name.
# This should not need to be changed unless the auto detection fails.
SECTION="$( basename $( pwd ) )"
export SECTION

if [ ! -f .buildlist."$SECTION" ]; then
	echo ""
	echo "**********************************************************************"
	echo "The buildlist either doesn't exist, or is of a different architecture."
	echo "** .buildlist.$SECTION is needed **"
	echo "Exiting!"
	echo "**********************************************************************"
	exit 1
fi

# Packages to build.
# The package list is read in from .buildlist in the current directory, with
# any comments and blank lines removed.
PACKAGES="$( egrep -v "^#|^$" .buildlist."$SECTION" | cut -d'#' -f1 )"

function list_packages() {
  local PACKAGE
  echo "The following packages are built in this section, listed in processing order:"

  ( for PACKAGE in $PACKAGES 
    do
      echo -n "$PACKAGE, "
    done ) | sed -e 's/, $//' | fmt -w 74 | sed -e 's/^/    /g'
}

function find_package_files() {
  # $1 = Directory to look for files in [required]
  # $2 = Package name or regex to match.  An empty string matches all.
  # $3 = Package version or regex to match.  An empty string matches all.
  # $4 = Package architecture or regex to match.  An empty string matches all.
  # $5 = Package build tag or regex to match.  An empty string matches all.
  # $6 = File extension or regex to match.  An empty string means no extension.
  # Note: Remember to escape any regex characters used in fixed strings.

  [ -z "$1" ] || [ ! -d "$1" ] && return 1
  find $1 -maxdepth 1 -mindepth 1 2>/dev/null | \
    egrep "^.*/(${2:-.*})(-${3:-[^-]*})(-${4:-[^-]*})(-${5:-[^-.]*})($6)$" 2>/dev/null
  return $?
}

# Environment.
PACKAGESDIR=${PACKAGESDIR:-/$ARCH}
export PACKAGESDIR

# Option defaults.
NOPATCHESDIR=0
NOINSTALL=0

# This check compares a list of source directories with the list of the
# packages in the build list and warns of any missing package names 
# in either of the two.

DIRTEMPFILE=$(mktemp $SM_PARENTTMP/DIRECTORYNAMES."$SECTION".XXXXXX)
DIRFILETEMPPATH="$DIRTEMPFILE"
DIRLIST=$(find . -type d -maxdepth 1 -mindepth 1 | sed 's@./@@' | sort > $DIRFILETEMPPATH)

PACKTEMPFILE=$(mktemp $SM_PARENTTMP/BUILDFILENAMES."$SECTION".XXXXXX)
PACKFILETEMPPATH="$PACKTEMPFILE"
sort .buildlist.$SECTION > $PACKFILETEMPPATH
  
DIRECTORYCOUNT="$( wc -l < $DIRTEMPFILE )"
BUILDLISTCOUNT="$( wc -l < $PACKTEMPFILE )"

# Get number of total packages
TOTALPKGNUMBER="$(wc -l < .buildlist.$SECTION)"
export TOTALPKGNUMBER

if diff -u "$DIRFILETEMPPATH" "$PACKFILETEMPPATH" > /dev/null 2>&1 ; then
  DIFFSTATUS="0"
else
  DIFFSTATUS="1"
fi

if [ "$DIFFSTATUS" != "0" ]; then 
  echo "*********************************************************************"
  echo "** Warning: In section '"$SECTION"', the number of packages in the"
  echo "** hidden file '.buildlist."$SECTION"' is different to the number of"
  echo "** package directories. Some packages may not have been added to"
  echo "** this file/section directory. They are listed below:"
  echo ""

  diff -u "$DIRFILETEMPPATH" "$PACKFILETEMPPATH" || true
  echo ""
  diff -u "$PACKFILETEMPPATH" "$DIRFILETEMPPATH" || true

  echo ""
  echo "** Building anyways :-) "
  echo "*********************************************************************"
  sleep 2

fi
rm -f $PACKFILETEMPPATH $DIRFILETEMPPATH

# Parse command line arguments.
while [ $# -gt 0 ]; do
  if [ "$1" = "-help" ] || [ "$1" = "--help" ]; then
    usage
    exit 0
  elif [ "$1" = "-list" ] || [ "$1" = "--list" ]; then
    list_packages
    exit 0
    shift
  else
    echo "${0##*/}: Unknown option: $1"
    echo "Try: $0 --help"
    exit 1
  fi
done

# Temporary space, package and log file storage.
mkdir -p $PKGDEST $LOGSDIR/$SECTION

      echo "*********************************************************************"
      echo "** Building section '$SECTION'..."
      echo "*********************************************************************"

# Process packages.
( for PACKAGE in $PACKAGES 
  do
    # Build defaults.
    SKIP_BUILD=0
    SUBDIR=$PACKAGESDIR/$SECTION

      echo "*********************************************************************"
      echo "*** Processing package '$PACKAGE'..."
      echo "*********************************************************************"

    # Sanity checks.
    [ ! -e "$PACKAGE/$PACKAGE.SMBuild" ] && {
      echo "*********************************************************************"
      echo "*** Error: '$PACKAGE.SMBuild' not found."
      echo "*********************************************************************"
      exit 1
    }
    [ ! -x "$PACKAGE/$PACKAGE.SMBuild" ] && {
      echo "*********************************************************************"
      echo "*** Error: '$PACKAGE.SMBuild' is not executable."
      echo "*********************************************************************"
      exit 1
    }

    # Get package version and build numbers from the package SMBuild.
    declare PACKAGE_$( egrep -m 1 "^VERSION=.*" $PACKAGE/$PACKAGE.SMBuild )
    declare PACKAGE_$( egrep -m 1 "^BUILD=.*" $PACKAGE/$PACKAGE.SMBuild )

    # Check that we got a version and build.
    [ -z "$PACKAGE_VERSION" ] || [ -z "$PACKAGE_BUILD" ] && {
      echo "*********************************************************************"
      echo "*** Error: failed to get VERSION or BUILD from '$PACKAGE.SMBuild'"
      echo "*********************************************************************"
      exit 1
    }

    # Check if the package should be rebuilt, and where it should be put.
    # The assumption is to always rebuild and put packages in the main
    # directory, unless modified by the checks below.
    if find_package_files "$PKGDEST/$SUBDIR" "${PACKAGE//+/\+}" \
      "" "" "" "\.$PKGEXT" >/dev/null
    then
      if find_package_files "$PKGDEST/$SUBDIR" "${PACKAGE//+/\+}" \
        "${PACKAGE_VERSION//-/_}" "" "$PACKAGE_BUILD" "\.$PKGEXT" >/dev/null
      then
        # Package with same version/build was found in the main directory.
        SKIP_BUILD=1
      fi
    fi

    # Build package if required.
    if [ "$SKIP_BUILD" = "0" ]; then
      echo "*********************************************************************"
      echo "*** Building package '$PACKAGE'..."
      echo "*********************************************************************"
      # Get the current package number from the build list
      CURRENTPKGNUMBER="$(grep -wn "$PACKAGE" .buildlist.$SECTION | cut -d: -f 1)"
      export CURRENTPKGNUMBER
      mkdir -p $PKGDEST/$SUBDIR
      ( cd $PACKAGE && export PKGDEST=$PKGDEST/$SUBDIR &&
        bldpkg 2>&1 ) | \
        tee $LOGSDIR/$SECTION/$PACKAGE-$SECTION-$HOSTTYPE.log.txt
      # Unset $CURRENTPKGNUMBER. We don't want issues when a new one comes in
      ERR=${PIPESTATUS[0]}
      if [ "$ERR" != "0" ] ; then 
        unset CURRENTPKGNUMBER
        echo "*** Error: '$PACKAGE' build failed."
        exit $ERR
      else
        unset CURRENTPKGNUMBER
        VERSION="$(cat $SM_PARENTTMP/$PACKAGE.VERSION)"
        BUILD="$(cat $SM_PARENTTMP/$PACKAGE.BUILD)"
        mv $LOGSDIR/$SECTION/$PACKAGE-$SECTION-$HOSTTYPE.log.txt \
          $LOGSDIR/$SECTION/$PACKAGE-$VERSION-$BUILD-$SECTION-$HOSTTYPE.log.txt
        rm -f $SM_PARENTTMP/$PACKAGE.{APP,VERSION,BUILD}
      fi
    else
      echo "*********************************************************************"
      echo "*** Skipping build of '$PACKAGE' - package up to date."
      echo "*********************************************************************"

    fi

    if [ "$NOINSTALL" = "0" ]; then
      echo
      echo "*********************************************************************"
      echo "*** Installing '$PACKAGE'..."
      echo "*********************************************************************"
      upgradepkg --install-new $( find_package_files "$PKGDEST/$SUBDIR" \
        "${PACKAGE//+/\+}" "${PACKAGE_VERSION//-/_}" "" "$PACKAGE_BUILD" "\.$PKGEXT" ) || {
        echo
        echo "*********************************************************************"
        echo "*** Error: failed to install '$PACKAGE'."
        echo "*********************************************************************"
        exit 1
      }
    else
      echo
      echo "*********************************************************************"
      echo "*** Warning: not installing '$PACKAGE'."
      echo "*********************************************************************"
    fi
  done

  echo "*********************************************************************"
  echo "** Finished building section '$SECTION'."
  echo "** SMLinux packages are in '$PKGDEST/$ARCH/$SECTION'."
  echo "** Section build logs are in '$LOGSDIR/$SECTION'."
  echo "*********************************************************************"
  echo "** Section build time was $( runtime $SECONDS )"
  echo "*********************************************************************"
) 2>&1 | tee $LOGSDIR/$SECTION-$ARCH.log.txt

# Return the exit status from the sub-shell, not the tee command.
exit ${PIPESTATUS[0]}
