#!/bin/sh
# This script is useful to rebuild a package from existing installed files
# Good for users on slow connections that want to share, say, kdelibs but have
# already cleaned their cache.  Many other useful things as well
#
# TODO check the BACKUP section and change pkgrel if anything has changed

pacinfo ()
{
    [ $# -ne 2 ] && return 1
    #use echo to strip spaces
    echo $(pacman -Qi ${1} | grep "${2}" | cut -d: -f2-)
}

make_pkginfo ()
{
    echo "# Generated by re-pacman 1.0.0"
    echo "# On $(date)"
    echo "pkgname =$(pacinfo ${1} Name)"
    echo "pkgver =$(pacinfo ${1} Version)"
    echo "pkgdesc =$(pacinfo ${1} Description)"
    echo "url =$(pacinfo ${1} URL)"
    echo "builddate =$(pacinfo ${1} 'Build Date')"
    echo "packager =$(pacinfo ${1} Packager)"
    echo "size =$(pacinfo ${1} Size)"
    echo "arch =$(pacinfo ${1} Architecture)"
    deps=$(pacinfo ${1} 'Depends On')
    for d in ${deps}; do
        echo "depend = ${d}"
    done
}

if [ $# -ne 1 ]; then
    echo "usage: re-pacman <installed package name>"
    exit 1
fi

ver=$(pacinfo ${1} Version)
if [ "x${ver}" = "x" ]; then
    echo "Package '${1}' not found, aborting."
    exit 1
fi

echo ":: Cleaning up old files"
rm -f .PKGINFO .FILELIST "${1}-${ver}.pkg.tar.gz"

echo ":: Building PKGINFO"
make_pkginfo ${1} > .PKGINFO
echo ":: Building FILELIST"
pacman -Ql ${1} | cut -d' ' -f2- > .FILELIST

flist=".PKGINFO .FILELIST"
flist="${flist} $(pacman -Ql ${1} | sed 's|\w* \(.*\)|/\1|g' | grep -v '/$')"

echo ":: Building final package tarball"
echo ${flist} | tr ' ' '\n' | tar czf "${1}-${ver}.pkg.tar.gz" -T - 2>/dev/null

rm -f .PKGINFO .FILELIST
echo ":: Package '${1}-${ver}.pkg.tar.gz' is now ready for installation"