#!/bin/bash

# lm_sensors.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter <mozes@slackware.com>

# 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

# Determine the CFLAGS for the known architectures:
case $ARCH in
   arm)     export SLKCFLAGS="-O2 -march=armv4t"
            export LIBDIRSUFFIX="" ;;
   *)       export SLKCFLAGS="-O2" ;;
esac

# Extract source:
tar xvvf $CWD/$PKGNAM-$VERSION.tar.bz2
cd $PKGNAM-$VERSION || exit 1
slackhousekeeping

# Configure:
zcat $CWD/lm_sensors.makefile.diff.gz | patch -p1 --verbose || failpatch

# Build:
make user LIBDIR=/usr/lib${LIBDIRSUFFIX} || exit 1

# Install:
make user_install LIBDIR=/usr/lib${LIBDIRSUFFIX} || failinstall

# Nope:
rm -f $PKG/usr/lib/*.a
rm -rf $PKG/usr/include/linux

# Do the .new thing with the config file:
mv $PKG/etc/sensors3.conf $PKG/etc/sensors3.conf.new

# Add a documentation directory:
mkdir -p $PKG/usr/doc/$PKGNAM-$VERSION/doc
cp -a \
  CHANGES CONTRIBUTORS COPYING* INSTALL README* doc \
  $PKG/usr/doc/${PKGNAM}-$VERSION

# Install doinst script:
mkdir -p $PKG/install
install -m644 $CWD/slack-desc $PKG/install/
cat << EOF > $PKG/install/doinst.sh
#!/bin/sh
config() {
  NEW="\$1"
  OLD="\$(dirname \$NEW)/\$(basename \$NEW .new)"
  # If there's no config file by that name, mv it over:
  if [ ! -r \$OLD ]; then
    mv \$NEW \$OLD
  elif [ "\$(cat \$OLD | md5sum)" = "\$(cat \$NEW | md5sum)" ]; then # toss the redundant copy
    rm \$NEW
  fi
  # Otherwise, we leave the .new copy for the admin to consider...
}
config etc/sensors3.conf.new
EOF

# If necessary, start the fakeroot server so we can set file/dir ownerships:
start_fakeroot

# Apply generic Slackware packaging policies:
cd $PKG
slackstripall   # strip all .a archives and all ELFs
slackgzpages -i # compress man & info pages and delete usr/info/dir
slackslack      # chown -R root:root, chmod -R og-w, slackchown, slack644docs
slackmp         # run makepkg -l y -c n

# Perform any final checks on the package:
cd $PKG
slackhlinks     # search for any hard links
