#!/bin/sh -e

HOOKS=/var/cache/pbuilder/hooks
EXTRA=/var/cache/pbuilder/extra
STABLEDIST=bullseye

case "$1" in
    configure)
        chmod -R g+w "$HOOKS"
        chgrp -R admin "$HOOKS"
        if [ ! -d "$EXTRA" ] ; then
            for dist in $STABLEDIST sid ; do
                mkdir -p "$EXTRA/$dist/packages"
                chmod -R g+w "$EXTRA/$dist/packages"
                chgrp -R admin "$EXTRA/$dist/packages"
            done
            if [ ! -L "$EXTRA/release" ] ; then
                ln -s sid "$EXTRA/release"
            fi
            chmod  -R g+w "$EXTRA"
            chgrp -R admin "$EXTRA"
            cd "$EXTRA/release" && apt-ftparchive packages . > Packages
            if [ $EXTRA/release/Packages ] ; then
                echo "$EXTRA/release/Packages successfully created."
            else
                echo "Failed to create $EXTRA/release/Packages."
                exit 1
            fi
        fi
        set -x
        if [ ! -d /var/cache/pbuilder/base.cow ] ; then
            cowbuilder --create
        fi
        if [ ! -d /var/cache/pbuilder/$STABLEDIST-base.cow ] ; then
            cowbuilder --create --distribution $STABLEDIST --basepath /var/cache/pbuilder/$STABLEDIST-base.cow
        fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

#DEBHELPER#
