#!/bin/bash

_write_metadata(){
echo -e "Package: $name"
#echo -e "Source: $source"
echo -e "Version: $version"
notnull $partof  && echo -e "Section: $partof"
notnull $priority && echo -e "Priority: $priority"
echo -e "Architecture: $arch"
echo -e "Maintainer: $maintainer <$email>"
echo -e "Installed-Size: $(du -s $INSTALLDIR | cut -f 1)"
notnull "$depends" && { echo -ne "Depends:"
for dep in ${depends[@]}
do
	echo -ne " $dep,"
done | sed "s/,$//g" ; echo
}
echo -e "Homepage: $homepage"
echo -e "Date: $(date +'%d/%m/%Y-%H:%M:%S')"
echo -e "Description: $description\n"
}

_create_metadata(){

	mkdir -p $PKGDIR/DEBIAN
	if [ -d "$debdir" ]; then
		cp -prfv $debdir/* $PKGDIR/DEBIAN
	else
		_write_metadata > $PKGDIR/DEBIAN/control
	fi
	find $INSTALLDIR/ -type d | xargs chmod 755
	find $INSTALLDIR/ -type f -exec md5sum {} \; > $PKGDIR/md5sums
}

_package(){
	if [ -f /var/lib/dpkg/status ] ; then
		cp -prf $INSTALLDIR/* $PKGDIR/
		dpkg -b $PKGDIR "$CURDIR/${name}_${arch}_${version}.deb"
	else
	 	cd $INSTALLDIR
	 	tar --xz -cvf $PKGDIR/data.tar.xz ./*
	 	cd $PKGDIR/DEBIAN
	 	tar --xz -cvf $PKGDIR/control.tar.xz *
	 	echo "2.0" > $PKGDIR/debian-binary
	 	cd $PKGDIR
	 	ar r "$CURDIR/${name}_${arch}_${version}.deb" debian-binary control.tar.xz data.tar.xz
	fi
} 

