#!/bin/sh
# gfsdel -- delete a package.

# Copyright (C) 2004 Henrik S. Hansen

# Author: Henrik S. Hansen <hsh@freecode.dk>
# $Date: 2004/10/24 19:22:52 $
# $Revision: 1.7 $

# This file is part of gfs.

# gfs is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your
# option) any later version.

# gfs is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
# License for more details.

# You should have received a copy of the GNU General Public License
# along with gfs; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA


# Synopsis: gfsdel package.

# Delete an installed package.  Searches for the log file, which ends
# with .addlog, in /usr/share/gfs.  You can just use the start of the
# package name, but this must then be unique.  If package name is only
# partial and not unique, complain and exit.  Else delete the files
# mentioned in the log, except those also present in other log files
# in /usr/share/gfs.  Log the files deleted in
# /usr/share/gfs/<package>.dellog.  Move the <package>.addlog to
# package.deleted.


if [ $# -ne 1 -o -z "$1" ] ; then
    echo "Usage: $0 package"
    exit 1
fi

cd /usr/share/gfs

# Find unique logfile
matched=$(mktemp)
find * -name "$1"'*.addlog' > $matched
if [ $(cat $matched | wc -l) -gt 1 ] ; then
    echo 'Log file not unique.'
    exit 1
elif [ $(cat $matched | wc -l) -lt 1 ] ; then
    echo 'Log file not found.'
    exit 1
else
    addlog=$(cat $matched)      # Files to remove
    pkgname=${addlog%.*}        # Full name of package
fi

rm -f $matched
echo "Logfile used: $addlog" >&2

# Files used by other packages
keep=$(mktemp)
find * ! -name $addlog | xargs cat > $keep

tmplog=$(mktemp)
for f in $(grep -v '^#' $addlog | tac) ; do
    # Skip files also used by other packages
    grep "^$f" $keep >/dev/null && \
        echo "$f used, so not deleted." >&2 && \
        continue

    if [ -f $f -o -h $f ] ; then
        rm -v $f >> $tmplog
    elif [ -d $f ] ; then
        rmdir -v $f >> $tmplog
    fi
done

log="$pkgname.dellog"
mv $addlog "$pkgname.deleted"
echo -e "# gfsdel $pkgname\n# $(date)" | cat - $tmplog >> $log
