#!/bin/bash

# x11.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter <mozes@slackware.com>
################################################################################
#
# Copyright 2007  Patrick Volkerding, Sebeka, MN, USA
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# To build only a single package group, specify it as $1, like:
# ./x11.SlackBuild lib
# To build only a single package, specify both the source directory
# and the name of the package, like:
# ./x11.SlackBuild lib libX11
################################################################################

echo "Command line: $@"

# Record toolchain & other info for the build log:
slackbuildinfo

# Paths to skeleton port's source & real Slackware source tree:
export CWD=$SLACKSOURCE/$PKGSERIES/$PKGNAM
export PORTCWD=$PWD

# Temporary build locations:
export TMPBUILD=$TMP/build-$PKGNAM
export PKG=$TMP/package-$PKGNAM
mkpkgdirs # Delete & re-create temporary directories then cd into $TMPBUILD
SLACK_X_BUILD_DIR=$TMPBUILD

# Clean failure log:
mkdir -vpm755 $PORTCWD/build-logs
rm -f $PORTCWD/build-logs/build-fails.log

# Functions:
pkgbase() {
  PKGEXT=$(echo $1 | rev | cut -f 1 -d . | rev)
  case $PKGEXT in
  'gz' )
    PKGRETURN=$(basename $1 .tar.gz)
    ;;
  'bz2' )
    PKGRETURN=$(basename $1 .tar.bz2)
    ;;
  'lzma' )
    PKGRETURN=$(basename $1 .tar.lzma)
    ;;
  'xz' )
    PKGRETURN=$(basename $1 .tar.xz)
    ;;
  *)
    PKGRETURN=$(basename $1)
    ;;
  esac
  echo $PKGRETURN
}

no_usr_share_doc() {
  # If there are docs, move them:
  if [ -d usr/share/doc ]; then
    mkdir -pm755 usr/doc
    mv -vf usr/share/doc/* usr/doc
    rmdir usr/share/doc
  fi
}

# Function to retrieve the package name.
# glibc-solibs-2.2-i386-1.t?z = glibc-solibs
function short_package_name () {
  local PACKAGENAME="$( echo $1 | rev | cut -d- -f4- | rev )"
  echo ${PACKAGENAME}
}

# Set the compile options for the $ARCH being used:
PKGARCH=$ARCH # ARCH is set from arm/build
. $PORTCWD/arch.use.flags

# Better have some binaries installed first, as this may not be
# in the "magic order".  I built mine by hand through trial-and-error
# before getting this script to work.  It wasn't that hard...  I think.  ;-)
( cd $CWD/src
  for x_source_dir in proto data util xcb lib app doc driver font xserver ; do
    # See if $1 is a source directory like "lib":
    if [ ! -z "$1" ]; then
      if [ ! "$1" = "${x_source_dir}" ]; then
        continue
      fi
    fi
    PKG=${SLACK_X_BUILD_DIR}/package-${x_source_dir}
    rm -rf $PKG
    mkdir -p $PKG
    ( cd $x_source_dir
      for x_pkg in *.tar.?z* ; do
        # Reset $PKGARCH to its initial value:
        PKGARCH=$ARCH
        PKGNAME=$(echo $x_pkg | rev | cut -f 2- -d - | rev)
        # Perhaps $PKGARCH should be something different:
        if grep -wq "^$PKGNAME" ${CWD}/noarch ; then
          PKGARCH=noarch
        fi 
        if grep -wq "^$PKGNAME" ${CWD}/package-blacklist ; then
          continue
        fi
        cd $SLACK_X_BUILD_DIR
        # If $2 is set, we only want to build one package:
        if [ ! -z "$2" ]; then
          if [ "$2" = "$PKGNAME" ]; then
            # Set $PKG to a private dir for the modular package build:
            PKG=$SLACK_X_BUILD_DIR/package-$PKGNAME
            rm -rf $PKG
            mkdir -p $PKG
          else
            continue
          fi
        else
          echo
          echo "Building from source ${x_pkg}"
          echo
        fi
        if grep -wq "^$PKGNAME" ${CWD}/modularize ; then
          # Set $PKG to a private dir for the modular package build:
          PKG=$SLACK_X_BUILD_DIR/package-$PKGNAME
          rm -rf $PKG
          mkdir -p $PKG
        fi

        # Now, if there's a local Slackware ARM version (which may be an alternate
        # version if the one in Slackware won't build), let's find it:
        # (this is very rare - which is why the logic of this bit of
        # code is awful; a real hack).
        if [ -f $PORTCWD/src/${x_source_dir}/${PKGNAME}-*.t*z ]; then
           echo "******************************************************"
           echo "*** Found local copy $PORTCWD/src/${x_source_dir}/${PKGNAME}*.t?z ****"
           echo "******************************************************"
           x_pkg=$( basename $PORTCWD/src/${x_source_dir}/${PKGNAME}-*.t*z )
           LOCATIONCWD=$PORTCWD
         else
           LOCATIONCWD=$CWD
        fi

        # Let's figure out the version number on the modular package:
        MODULAR_PACKAGE_VERSION=$(echo $x_pkg | rev | cut -f 3- -d . | cut -f 1 -d - | rev)
        rm -rf $(pkgbase $x_pkg)
#        tar xvvf $CWD/src/${x_source_dir}/${x_pkg} || exit 1
        tar xvvf $LOCATIONCWD/src/${x_source_dir}/${x_pkg} || exit 1
        cd $(pkgbase $x_pkg) || exit 1
        slackhousekeeping

        echo "*** Modular package version: $MODULAR_PACKAGE_VERSION ***"

        # Determine whether the version of this particular modular package
        # is the same as the last version we built.  If it isn't then
        # we reset the BUILD to 1, regardless of whether the indibuild script
        # was specified as a rebuild or upgrade.
        # This allows us to run this x11.SlackBuild to do mass updates (say with a new X release)
        # without having to manually keep track of what is new and what is 
        # just a rebuild.
        # 
        if [ -r $PORTCWD/build-nums/${PKGNAME} ]; then
           source $PORTCWD/build-nums/${PKGNAME}
           # We found the previous details:
           echo "Package: $PKGNAME"
           echo "Previous built version: ${_PKGVER}"
           echo "Previous build #: $MODBUILD"
           echo "New version: $MODULAR_PACKAGE_VERSION"

           # _PKGVER is stored inside the package file name and indicates
           # the last build that was done.
           # The "indibuild" script sets just the build number to 1 when Upgrading
           # packages, so the logic below isn't useful if you're using that script.
           if [ "$MODULAR_PACKAGE_VERSION" != "$_PKGVER" -o -z "$_PKGVER" ]; then
              # Version doesn't match (let's assume it's an upgrade)
              # or the version string is empty.  Store new details:
              echo "*** Detected version change (or no previous version) for $PKGNAME ***"
              echo "*** Storing new version & setting BUILD to 1 ***"
              echo "_PKGVER=$MODULAR_PACKAGE_VERSION" > $PORTCWD/build-nums/${PKGNAME}
              echo "MODBUILD=1" >> $PORTCWD/build-nums/${PKGNAME}
          else
             # The version matched, so increment the BUILD *unless* the "indibuild" script
             # has set MODBUILDNOBUMP (which is used when we're rebuilding packages
             # to test fixes and so on prior to a public tree push -- otherwise by now 
             # the public tree would be into the hundred build numbers ;-) ).
              echo "_PKGVER=$MODULAR_PACKAGE_VERSION" > $PORTCWD/build-nums/${PKGNAME}
              if [ -z "$MODBUILDNOBUMP" ]; then
                 let MODBUILD++
                 echo "*** Incrementing the BUILD number to $MODBUILD ***"
                else
                 echo "*** Not incrementing build number (MODBUILDNOBUMP is set) ***"
                 echo "*** (could also be because the indibuild script is being used) ***"
              fi
              echo "MODBUILD=$MODBUILD" >> $PORTCWD/build-nums/${PKGNAME}
          fi
         else
           # No build information found for this modular package so we'll 
           # create it ready for next time.
           echo "*** No previous build information found: storing current version and build ***"
           echo "_PKGVER=$MODULAR_PACKAGE_VERSION" > $PORTCWD/build-nums/${PKGNAME}
           echo "MODBUILD=1" >> $PORTCWD/build-nums/${PKGNAME}
        fi

        # If any patches are needed, call this script to apply them:
        if [ -r $CWD/patch/${PKGNAME}.patch ]; then
          . $CWD/patch/${PKGNAME}.patch
        fi
        # And then any local ARMedslack patches:
        if [ -r $PORTCWD/patch/${PKGNAME}.patch ]; then
          . $PORTCWD/patch/${PKGNAME}.patch
        fi

        # ./configure, using custom configure script if needed:
        # autoreconf
        # Check if we have a $PKG specific Slackware ARM configure script first:
        if [ -r $PORTCWD/configure/${PKGNAME} ]; then
           echo "*************************************************"
           echo "*** Using local configure: $PORTCWD/configure/${PKGNAME} *********"
           echo "*************************************************"
           . $PORTCWD/configure/${PKGNAME}
           # No, perhaps a Slackware x86 one?
           elif [ -r $CWD/configure/${PKGNAME} ]; then
                # . $CWD/configure/${PKGNAME} 
                # We need to add "gnueabi" otherwise building doesn't
                # work for the EABI ARM port:
                sed -e 's?-slackware-linux?-slackware-linux-gnueabi?g' $CWD/configure/${PKGNAME} > armconfigure
                # No autoconf "configure" script shipped by the vendor? try and make one.
                [ ! -x ./configure ] && autoreconf -vif
               . armconfigure
            else
                # This is the default configure script:
                # . $CWD/configure/configure 
                sed -e 's?-slackware-linux?-slackware-linux-gnueabi?g' $CWD/configure/configure > armconfigure
                # No autoconf "configure" script shipped by the vendor? try and make one.
                [ ! -x ./configure ] && autoreconf -vif
                . armconfigure
        fi
        # I had make -j1 here for xorg 7.2 but I don't know why - whether
        # anything more broke on ARM... let's see!
        if ! make $NUMJOBS ; then
          echo "******* $PKGNAME FAILED MAKE *******" 
          touch ${SLACK_X_BUILD_DIR}/${PKGNAME}.failed
          echo "Failed build for $PKGNAME" >> $PORTCWD/build-logs/build-fails.log
          continue
        fi

        # Install into package:
        make install DESTDIR=$PKG
        if [ ! -z "$MODULAR_PACKAGE_VERSION" ]; then 
          mkdir -p $PKG/usr/doc/${PKGNAME}-${MODULAR_PACKAGE_VERSION}
         else
           # Use the main X11 version number:
          mkdir -p $PKG/usr/doc/${PKGNAME}-${VERSION}
         fi
        cp -favv \
          AUTHORS* COPYING* INSTALL* README* NEWS* TODO* \
          $PKG/usr/doc/${PKGNAME}-*/

        # Trim down a "ChangeLog" file:
        if [ ! -z "$MODULAR_PACKAGE_VERSION" ]; then 
           changelogliposuction ChangeLog $PKGNAME $MODULAR_PACKAGE_VERSION
         else
           changelogliposuction ChangeLog $PKGNAME $VERSION
        fi 

        # Get rid of zero-length junk files:
        ( cd $PKG/usr/doc
          find . -type f -size 0 -exec rm --verbose "{}" \;
          rmdir --verbose * )

        # Strip binaries:
        ( cd $PKG
          find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
          find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
          find . | xargs file | grep "current ar archive" | grep ELF | cut -f 1 -d : | xargs strip -g 2> /dev/null
        )

        # If there's any special post-install things to do, do them:
        if [ -r $CWD/post-install/${PKGNAME}.post-install ]; then
          RUNSCRIPT=$(mktemp -p $TMP) || exit 1
          cat $CWD/post-install/${PKGNAME}.post-install | sed -e "s#usr/lib#usr/lib${LIBDIRSUFFIX}#g" > $RUNSCRIPT
          . $RUNSCRIPT
          rm -f $RUNSCRIPT
        fi
        # If there are ARMedslack specific post-install things, do them:
        if [ -r $PORTCWD/post-install/${PKGNAME}.post-install ]; then
          . $PORTCWD/post-install/${PKGNAME}.post-install
        fi

        # If this package requires some doinst.sh material, add it here:
        if [ -r $CWD/doinst.sh/${PKGNAME} ]; then
          mkdir -p $PKG/install
          cat $CWD/doinst.sh/${PKGNAME} >> $PKG/install/doinst.sh
        fi

        # If this is a modular package, build it here:
        if [ -d $SLACK_X_BUILD_DIR/package-$PKGNAME ]; then
          cd $PKG
          slackgzpages -i # compress man & info pages and delete usr/info/dir
          slackslack      # chown -R root:root, chmod -R og-w, slackchown, slack644docs
          no_usr_share_doc          
          mkdir -p $PKG/install
          if [ -r $CWD/slack-desc/${PKGNAME} ]; then
            cat $CWD/slack-desc/${PKGNAME} > $PKG/install/slack-desc
          else
            touch $PKG/install/slack-desc-missing
          fi
          if [ -r $PORTCWD/build-nums/${PKGNAME} ]; then
#          if [ -r $CWD/build/${PKGNAME} ]; then
#            MODBUILD=$(cat $CWD/build/${PKGNAME})
          # Look in the port arch's source dir for a build number for this package:
#            MODBUILD=$(cat $PORTCWD/build-nums/${PKGNAME})
          source $PORTCWD/build-nums/${PKGNAME}
          else
            MODBUILD=$BUILD  ## use the version set in the "arm/build" script.
          fi
          if [ -r $CWD/makepkg/${PKGNAME} ]; then
          # We need to make tgz packages for Slackware ARM because it takes a lot
          # longer to decompress .txz on ARM.
             sed -e 's?.txz?.tgz?g' $CWD/makepkg/${PKGNAME} > ${SLACK_X_BUILD_DIR}/${PKGNAME}.makepkg
             BUILD=$MODBUILD . ${SLACK_X_BUILD_DIR}/${PKGNAME}.makepkg
          #  BUILD=$MODBUILD . $CWD/makepkg/${PKGNAME}
            # Install & upgrade the new packages just built:
            upgradepkg --reinstall --install-new ${SLACK_X_BUILD_DIR}/*.t?z
            # Delete the previous versions from the armedslack tree:
            ( cd ${SLACK_X_BUILD_DIR}
              for i in *-[0-9]*.t?z ; do
                rm -fv $PKGSTORE/x/$( short_package_name $i )-*.{txt,t?z,asc}
              done )
            # Move the new packages into the armedslack tree:
            ( cd ${SLACK_X_BUILD_DIR}
              mv -fv *.t?z $PKGSTORE/x/ )
          else
           echo "*** Did not find a modular package-specific makepkg; using defaults.. ***"
            makepkg -l y -c n ${SLACK_X_BUILD_DIR}/${PKGNAME}-${MODULAR_PACKAGE_VERSION}-${PKGARCH}-${MODBUILD}.tgz
            # Install & upgrade the new packages just built:
            upgradepkg --reinstall --install-new ${SLACK_X_BUILD_DIR}/*.t?z
            # Delete the previous versions from the armedslack tree:
            ( cd ${SLACK_X_BUILD_DIR}
              for i in *-[0-9]*.t?z ; do
                rm -fv $PKGSTORE/x/$( short_package_name $i )-*.{txt,t?z,asc}
              done )
            # Move the new packages into the armedslack tree:
            ( cd ${SLACK_X_BUILD_DIR}
              mv -fv *.t?z $PKGSTORE/x/ )
          fi
        fi

        # Reset $PKG to assume we're building the whole source dir:
        PKG=${SLACK_X_BUILD_DIR}/package-${x_source_dir}

      done

      # Nothing here?  Must have been fully modular. :-)
      if [ ! -d ${SLACK_X_BUILD_DIR}/package-${x_source_dir}/etc -a \
        ! -d ${SLACK_X_BUILD_DIR}/package-${x_source_dir}/usr ]; then
        continue
      fi

      # Build an "x11-<sourcedir>" package for anything that wasn't built modular:
      # It's safer to consider these to have binaries in them. ;-)
      PKGARCH=$ARCH
      cd $PKG
      slackgzpages -i # compress man & info pages and delete usr/info/dir
      slackslack      # chown -R root:root, chmod -R og-w, slackchown, slack644docs
      no_usr_share_doc
      # If there are post-install things to do for the combined package,
      # we do them here.  This could be used for things like making a
      # VERSION number for a combined package.  :-)
      if [ -r $CWD/post-install/x11-${x_source_dir}.post-install ]; then
        . $CWD/post-install/x11-${x_source_dir}.post-install
      fi
      mkdir -p $PKG/install
      if [ -r $CWD/slack-desc/x11-${x_source_dir} ]; then
        cat $CWD/slack-desc/x11-${x_source_dir} > $PKG/install/slack-desc
      else
        touch $PKG/install/slack-desc-missing
      fi
      if [ -r $CWD/doinst.sh/x11-${x_source_dir} ]; then
        cat $CWD/doinst.sh/x11-${x_source_dir} >> $PKG/install/doinst.sh
      fi
      if [ -r $CWD/build/x11-${PKGNAME} ]; then
        SRCDIRBUILD=$(cat $CWD/build/x11-${PKGNAME})
      else
        SRCDIRBUILD=$BUILD
      fi
      if [ -r $CWD/makepkg/${PKGNAME} ]; then
        BUILD=$MODBUILD . $CWD/makepkg/${PKGNAME}
            # Install & upgrade the new packages just built:
            upgradepkg --reinstall --install-new ${SLACK_X_BUILD_DIR}/*.t?z
            # Delete the previous versions from the armedslack tree:
            ( cd ${SLACK_X_BUILD_DIR}
              for i in *-[0-9]*.t?z ; do
                rm -fv $PKGSTORE/x/$( short_package_name $i )-*.{txt,t?z,asc}
              done )
            # Move the new packages into the armedslack tree:
            ( cd ${SLACK_X_BUILD_DIR}
              mv -fv *.t?z $PKGSTORE/x/ )
      else
        makepkg -l y -c n ${SLACK_X_BUILD_DIR}/x11-${x_source_dir}-${VERSION}-${PKGARCH}-${SRCDIRBUILD}.tgz
            # Install & upgrade the new packages just built:
            upgradepkg --reinstall --install-new ${SLACK_X_BUILD_DIR}/*.t?z
            # Delete the previous versions from the armedslack tree:
            ( cd ${SLACK_X_BUILD_DIR}
              for i in *-[0-9]*.t?z ; do
                rm -fv $PKGSTORE/x/$( short_package_name $i )-*.{txt,t?z,asc}
              done )
            # Move the new packages into the armedslack tree:
            ( cd ${SLACK_X_BUILD_DIR}
              mv -fv *.t?z $PKGSTORE/x/ )
      fi
    )
  done
)

exit 0

# I don't think I'll be using the following stuff, since I went for the latest in
# "individual", rather than a release.  That was mostly because version 7.1 depends
# on a version of Mesa that won't build against kernel headers this new (&etc.).

# If environment variable "REFRESH" is exported, start by refreshing the source tree:
# export REFRESH yes
if [ ! -z "$REFRESH" ]; then
  # Only works once, unless you uncomment above.
  unset REFRESH
  ( cd patches
    lftp -c \
    "lftp ftp://ftp.x.org:/pub/X11R7.1/patches
     mirror --delete --dereference .
     exit"
    chmod 644 *
  )
  ( cd src
    mkdir -p update everything
    for dir in app data deprecated doc driver extras font lib proto util xserver ; do
      # We won't really download "update", as problems ensue.  Plus, --dereference is
      # bringing us updated files when needed, so it's redundant (like "everything").
      if [ ! -d $dir ]; then
        mkdir $dir
      fi
      ( cd $dir
        lftp -c \
        "lftp ftp://ftp.x.org:/pub/X11R7.1/src/$dir
         mirror -c --delete --dereference --include-glob "*.tar.bz2" .
         exit"
        chmod 644 *
      )
    done
  )
fi

echo
echo "***************************************************************"
echo "** REMEMBER: The finished packages are in the temporary build *"
echo "**           space:                                           *"
echo "** $SLACK_X_BUILD_DIR "
echo
