#!/bin/sh

: ${BINDIR:=/usr/local/samba/bin}

: ${builddir:=.}
: ${srcdir:=.}
: ${STRIP:=}
: ${CHMOD:=chmod}
: ${PACKAGE:=samba}
: ${TARGET:="bin/smbd bin/nmbd"}
: ${ARCH:=arm}
: ${REV:=1}

IPKDIR=${builddir}/ipk
PKGDIR=${builddir}/ipk.pkg

LANG=C; export LANG
LC_ALL=C; export LC_ALL
LC_COLLATE=C; export LC_COLLATE

HEAD=`tail ${srcdir}/include/version.h`
VER=`expr "${HEAD}" : '.*\"\(.*\)\".*'`
DIST=`whoami`@`hostname -d`

trap "rm -rf ${IPKDIR} ${PKGDIR}" 1 2 13 15

[ -d "${IPKDIR}" ] && rm -rf ${IPKDIR}
mkdir ${IPKDIR}
[ -d "${PKGDIR}" ] && rm -rf ${PKGDIR}
mkdir ${PKGDIR}
mkdir ${PKGDIR}/CONTROL
for p in ${TARGET}; do
	case `dirname ${p}` in
	bin|script)
		[ -d "${PKGDIR}/${BINDIR}" ] || ${srcdir}/script/mkinstalldirs ${PKGDIR}/${BINDIR}
		;;
	/*)
		[ -d "${PKGDIR}${p}" ] || ${srcdir}/script/mkinstalldirs ${PKGDIR}${p}
		;;
	esac
done

for p in ${TARGET}; do
	f=`basename ${p}`
	[ -e "${srcdir}/${p}" ] && case `dirname ${p}` in
	bin)
		cp -pr ${srcdir}/${p} ${PKGDIR}/${BINDIR}
		[ -z "${STRIP}" ] || ${STRIP} ${PKGDIR}/${BINDIR}/${f}
		${CHMOD} a+rx ${PKGDIR}/${BINDIR}/${f}
		;;
	script)
		cp -pr ${srcdir}/${p} ${PKGDIR}/${BINDIR}
		${CHMOD} a+rx ${PKGDIR}/${BINDIR}/${f}
		;;
	ipk.tmp)
		cp -pr ${srcdir}/${p} ${PKGDIR}
		;;
	esac
done
cat > ${PKGDIR}/CONTROL/control <<EOF
Package: ${PACKAGE}
Priority: optional
Section: net
Maintainer: ${DIST}
Architecture: ${ARCH}
Version: ${VER}-${REV}
Depends:
Description: a SMB network client tool
EOF
(cd ${PKGDIR}; tar cf - --exclude=CONTROL .) > ${IPKDIR}/data.tar
gzip -f ${IPKDIR}/data.tar
(cd ${PKGDIR}/CONTROL; tar cf - .) > ${IPKDIR}/control.tar
gzip -f ${IPKDIR}/control.tar
echo "2.0" > ${IPKDIR}/debian-binary
(cd ${IPKDIR}; tar cf - ./debian-binary ./data.tar.gz ./control.tar.gz) \
	| gzip -cf > ${builddir}/${PACKAGE}_${VER}-${REV}_${ARCH}.ipk
rm -rf ${IPKDIR} ${PKGDIR}
