#!/bin/sh
# vim:ts=8:et:fdm=marker
#
# dwww-refresh-cache -- refreshes dwww cache directory
#
# Part of the dwww package.  Written by Robert Luberda.
#
# "@(#)dwww:$Id: dwww-refresh-cache,v 1.4 2005-10-05 21:25:04 robert Exp $"

set -e

. /usr/share/dwww/functions.sh && dwww_initialize  || exit 1



echo -n "checking cache directory: $dwww_cache_dir..."
dwww_setup_cache_dir
echo done

# always remove temporary files, generated mostly by index++
echo -n "removing temporary files in cache dir..."
find "$dwww_cache_dir" -maxdepth 1 \
        -atime +2 \( -name '*.tmp.*' \
        -o -name '[0-9]*.[0-9]*' \) \
        -type f -print0 | xargs -0 rm -f
echo done


# remove accessed documents cache
if [ -n "$DWWW_KEEPDAYS" ] ; then
        echo -n "removing stale cache entries..."
        find "$dwww_cache_dir" -maxdepth 3 \
                 -atime +"$DWWW_KEEPDAYS" -name '[^.]*' \
                ! -name 'dwww.swish++.index' \
                ! -name '*.dat' \
                -type f -print0 | xargs -0 rm -f
        echo done

        su -s /bin/sh "$DWWW_CGIUSER" -c '/usr/sbin/dwww-cache --clean' || true

fi

pkglist="$dwww_cache_dir/pkglist.tmp.$$"

if [ -n "$DWWW_QUICKFIND_DB" ] || [ -n "$DWWW_DOCBASE2PKG_DB" ] ; then
        echo -n "generating installed packages and programs list..."
        LC_ALL=C dpkg --search '*' > "$pkglist"
        echo "done"
fi


if [ -n "$DWWW_DOCBASE2PKG_DB" ] ; then
        echo -n "creating doc-base files to packages mapping file..."
        grep '/usr/share/doc-base/' "$pkglist" | perl -ne '
                print $_ if s/^(\S*):\s*\/usr\/share\/doc-base\/(.*)$/$2\01$1/;
        ' > "$DWWW_DOCBASE2PKG_DB.tmp.$$"
        mv -f "$DWWW_DOCBASE2PKG_DB.tmp.$$" "$DWWW_DOCBASE2PKG_DB"
        chmod 644 "$DWWW_DOCBASE2PKG_DB"
        echo done
fi

if [ -n "$DWWW_QUICKFIND_DB" ] ; then
        echo -n "creating installed packages & programs cache..."
        dwww-quickfind --build "$DWWW_QUICKFIND_DB.tmp.$$" < "$pkglist"
        mv -f "$DWWW_QUICKFIND_DB.tmp.$$" "$DWWW_QUICKFIND_DB"
        chmod 644 "$DWWW_QUICKFIND_DB"
        echo done
fi

if [ -e "$pkglist" ] ; then
        rm -f "$pkglist"
fi
