#!/bin/sh
# preinst script for pymaemo-optify
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <new-preinst> `install'
#        * <new-preinst> `install' <old-version>
#        * <new-preinst> `upgrade' <old-version>
#        * <old-preinst> `abort-upgrade' <new-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

# This package has no effect inside Scratchbox
if [ -e /targets/links/scratchbox.config ]; then
    exit 0
fi

case "$1" in
    install)
        if [ -e /etc/init.d/pymaemo-optify ] &&
           [ -e /etc/default/pymaemo-optify ]; then
            # umount anything left, for some reason
            /etc/init.d/pymaemo-optify stop
            OPT_DIR="/opt/pymaemo"
            . /etc/default/pymaemo-optify
            # remove backup files from previous broken migrations
            rm -rf $OPT_DIR/bak.*
            for d in $BIND_MOUNTS; do
                # only attempt migration if source directories exist and are not
                # empty
                rmdir $d $OPT_DIR/$d 2>/dev/null || true
                if [ ! -d $d ]; then
                    continue
                fi
                if [ -d $OPT_DIR/$d ]; then
                    mkdir -p $OPT_DIR
                    tmpdir=`mktemp -d $OPT_DIR/bak.XXXXXX`
                    chmod 755 $tmpdir
                    echo "WARNING: destination \"$OPT_DIR$d\" exists, moving files to $tmpdir" >&2
                    # command below will create all components but delete the last one
                    mkdir -p $tmpdir/$d
                    rmdir $tmpdir/$d && mv $OPT_DIR/$d $tmpdir/$d || true
                fi
                echo "Migrating files from $d to $OPT_DIR$d..." >&2
                # command below will create all components but delete the last one
                mkdir -p $OPT_DIR/$d
                rmdir $OPT_DIR/$d && mv $d $OPT_DIR/$d || true
            done
        fi
    ;;

    upgrade)
    ;;

    abort-upgrade)
    ;;

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

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0


