#!/bin/bash
# Copyright 2014 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; version 2.1.
#
# This program 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: Benjamin Zeller <zeller.benjamin@canonical.com>

ARCHITECTURE=$1
FRAMEWORK=$2
SERIES=$3
NAME=$4

CLEANUP_DIRS=("/var/lib/schroot/chroots/${NAME}-${FRAMEWORK}-${ARCHITECTURE}")
CLEANUP_FILES=("/etc/schroot/chroot.d/${NAME}-${FRAMEWORK}-${ARCHITECTURE}")

click chroot -a $ARCHITECTURE -f $FRAMEWORK -n $NAME destroy

if [ $? -eq 0 ]
then
    echo "click target was removed successfully"
    exit 0
fi

for MOUNTPOINT in $(mount|grep $NAME-$FRAMEWORK-$ARCHITECTURE|awk '{print $3}')
do
    echo "Unmounting ${MOUNTPOINT}"
    umount $MOUNTPOINT
    if [ $? -ne 0 ]
    then
        echo "Unmount failed... trying to force"
        umount -f -l $MOUNTPOINT

        if [ $? -ne 0 ]
        then
            echo "Unmounting ${MOUNTPOINT} failed"
        fi
    fi
done

for FILE in $CLEANUP_FILES
do
    echo "Deleting ${FILE}"
    /bin/rm -f $FILE
    if [ $? -ne 0 ]
    then
        echo "Could not remove file: ${FILE}"
        exit 1
    fi
done

for DIR in $CLEANUP_DIRS
do
    echo "Deleting ${DIR}"
    /bin/rm -rf $DIR
    if [ $? -ne 0 ]
    then
        echo "Could not remove directory: ${DIR}"
        exit 1
    fi
done

echo "click target was removed successfully"
exit 0
