#!/bin/sh
# afbinit
#   A small program to load microcode into Elite3D framebuffers.

# This package includes the free (gratis) microcode blob 
# released by Sun Microsystems under an MIT-style license.
# For more information, see:
#   <http://lists.x.org/archives/xorg-devel/2009-December/004323.html>

test -n "${SLKDEBUG}" && set -x
set -o pipefail
set -e

### Set initial variables:
PKGNAME=afbinit
VERSION=1.0
PKGVER=1.0debian4
ARCH=${ARCH:-sparc}
REVISION=${REVISION:-0}

CWD=$(pwd)
TMP=${TMP:-/tmp}
PKG=${TMP}/package-${PKGNAME}
OUTPUT=${OUTPUT:-${TMP}}



### Housekeeping
## Sanitize the build site
mkdir -p ${TMP}
rm -rf ${PKG}
mkdir -p ${PKG}

## Unpack the sources
cd ${TMP}
rm -rf ${PKGNAME}-${VERSION}
tar zxvf ${CWD}/${PKGNAME}-${VERSION}.tar.gz
cd ${PKGNAME}-${VERSION}

## Unpack the ucode.
# We will unpack inside the afbinit directory for easy cleanup.
tar jxvf ${CWD}/afb-ucode.tar.bz2

## Normalize permissions
chown -R root:root .
find . -type f -exec chmod 0644 "{}" \;
find . -type d -exec chmod 0755 "{}" \;



### Patch
# We will add the Debian documentation and fixes patch to the mix
zcat ${CWD}/afbinit_1.0-4.diff.gz | \
   patch -p1 --verbose



### Build
make



### Install
## The executable:
mkdir -p ${PKG}/usr/sbin
cp afbinit ${PKG}/usr/sbin
chown -R root:bin ${PKG}/usr/sbin

## The ucode:
# We will install this in the new system-standard /lib/firmware/ directory,
# but we will provide a fallback symlink at the old /usr/lib/ location.
mkdir -p ${PKG}/lib/firmware/afb
cp -a afb-ucode/afb.ucode ${PKG}/lib/firmware/afb
mkdir -p ${PKG}/usr/lib
ln -s /lib/firmware/afb/afb.ucode ${PKG}/usr/lib/afb.ucode



### Fix-ups
# Strip the executable.
strip --strip-unneeded ${PKG}/usr/sbin/afbinit

# Add a startup script
mkdir -p ${PKG}/etc/rc.d/
cp rc.afb ${PKG}/etc/rc.d/rc.afb.new
chmod 0755 ${PKG}/etc/rc.d/rc.afb.new



### Documentation
## Man page
mkdir -p ${PKG}/usr/man/man8
cp -a debian/afbinit.8 ${PKG}/usr/man/man8/
gzip -9 ${PKG}/usr/man/man8/*

## Debian user docs
mkdir -p ${PKG}/usr/doc/${PKGNAME}-${PKGVER}
(  cd debian/
   cp -a \
     README.Debian \
     ${PKG}/usr/doc/${PKGNAME}-${PKGVER}
   cp -a \
     changelog \
     ${PKG}/usr/doc/${PKGNAME}-${PKGVER}/changelog.Debian
   cp -a \
     copyright \
     ${PKG}/usr/doc/${PKGNAME}-${PKGVER}/copyright.Debian
)

## Sun ucode README and license.
cp -a \
   afb-ucode/README \
   ${PKG}/usr/doc/${PKGNAME}-${PKGVER}/README.afb-ucode



### Build the package:
mkdir -p ${PKG}/install
cat ${CWD}/doinst.sh  > ${PKG}/install/doinst.sh
cat ${CWD}/slack-desc > ${PKG}/install/slack-desc
cd ${PKG}
makepkg -l y -c n ${OUTPUT}/${PKGNAME}-${PKGVER}-${ARCH}-${REVISION}.${PKGTYPE:-tgz}



### Clean up the extra stuff:
if [ "$1" = "--cleanup" ]; then
   rm -rf ${TMP}/${PKGNAME}-${VERSION}
   rm -rf ${PKG}
fi
