#!/bin/sh

## Written by Daniel R. <danielrodriguez.es@gmail.com>
 
# Based on scripts by the SlackBuilds.org project

PRGNAM=opensc-dnie
VERSION=1.4.6_2
ARCH=${ARCH:-i386}
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}

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

if [ "$ARCH" = "x86_64" ]; then
  TARGET="x86_64"
else
  TARGET="x86"
fi

if [ "$TARGET" = "x86" ]; then
  SRCFILE=Debian_Lenny_${PRGNAM}_$(echo $VERSION | tr "_" "-")_i386.deb.tar
  SRCDEB=${PRGNAM}_$(echo $VERSION | tr "_" "-")_i386.deb
elif [ "$TARGET" = "x86_64" ]; then
  SRCFILE=Debian_Lenny_${PRGNAM}_$(echo $VERSION | tr "_" "-")_amd64.deb.tar
  SRCDEB=${PRGNAM}_$(echo $VERSION | tr "_" "-")_amd64.deb
fi

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $PKG

tar xf $CWD/$SRCFILE $SRCDEB
ar x $SRCDEB data.tar.gz 
tar xxf data.tar.gz
rm $SRCDEB data.tar.gz

if [ "$TARGET" = "x86_64" ]; then
  mv $PKG/usr/lib $PKG/usr/lib64
  sed -i "s%= /usr/lib/%= /usr/lib64/%" \
    $PKG/usr/share/$PRGNAM/opensc.conf.dnie
  sed -i "s%libdir=\${exec_prefix}/lib%libdir=\${exec_prefix}/lib64%" \
    $PKG/usr/lib64/pkgconfig/*.pc
  sed -i "s%/usr/lib%/usr/lib64%g" \
    $PKG/usr/lib64/*.la
fi

mkdir -p $PKG/etc
cp $PKG/usr/share/$PRGNAM/opensc.conf.dnie $PKG/etc/opensc.conf.new

mv $PKG/usr/share/doc $PKG/usr
mv $PKG/usr/doc/$PRGNAM $PKG/usr/doc/$PRGNAM-$VERSION
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc
cat $CWD/doinst.sh > $PKG/install/doinst.sh

cd $PKG
chown -R root:root .
find . -type d -exec chmod 755 {} \;
chmod -R u+rw,go+r-w,a-s .

/sbin/makepkg -l y -c n -p $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.${PKGTYPE:-tgz}