#!/bin/bash

# Copyright (C) 2010-2019 by X2Go project, https://wiki.x2go.org
#       Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>
#       Moritz 'Morty' Struebe <Moritz.Struebe@informatik.uni-erlangen.de>
#       Mike Gabriel <mike.gabriel@das-netzwerkteam.de>

# X2Go 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.
#
# X2Go 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 this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

set -e

if echo $0 | egrep "^./bin/.*$" >/dev/null; then
	ETCDIR="etc/"
elif echo $0 | egrep "^./x2gothinclient_.*$" >/dev/null; then
	ETCDIR="../etc"
else
	ETCDIR=/etc/x2go
fi

source $ETCDIR/x2gothinclient_settings

TC_BASE="${TC_BASE:-/opt/x2gothinclient}"
TC_CHROOT="${TC_CHROOT:-$TC_BASE/chroot}"
TC_CONFIG="${TC_CONFIG:-$TC_BASE/etc}"
TC_TFTP_BOOT="${TC_TFTP_BOOT:-/srv/tftp}"

[ "x$USER" == "xroot" ] || {
	echo "ERROR: X2Go Thin Client management scripts have to run"
	echo "as super-user root."
	exit -2
}

echo "X2Go TCE cleanup..."
echo "-------------------"

echo "Hit <RETURN> to purge all X2Go TCE related files (chroot,"
echo "TCE config, PXE boot env)..."
echo
echo "Alternatively, hit STRG-C to cancel the operation now!!!"
read

# make sure, all chroot-internal mountpoints are gone...
for mountpoint in proc dev/pts sys; do
	while true; do
	cat /proc/mounts | grep "$TC_CHROOT/$mountpoint" >/dev/null && umount -l "$TC_CHROOT/$mountpoint" || break
	done
done

# CHROOT + TCE config
test -e "$TC_CHROOT" && {
	echo "Removing $TC_CHROOT..."
	rm -Rf "${TC_CHROOT}"
} || {
	echo "WARNING: X2Go Thin Client chroot does not exist"
	echo "at $TC_CHROOT. No cleanup necessary..."
}
test -e "$TC_CONFIG" && {
	echo "Removing $TC_CONFIG..."
	rm -Rf "${TC_CONFIG}"
} || {
	echo "WARNING: X2Go Thin Client config does not exist"
	echo "at $TC_CONFIG. No cleanup necessary..."
}

### PXE/Syslinux
test -e "$TC_TFTP_BOOT/pxelinux.cfg" && {
	echo "Emptying $TC_TFTP_BOOT..."
	rm -Rf "${TC_TFTP_BOOT}"/*
} || {
	echo "WARNING: X2Go PXE/Syslinux boot environment does not exist"
	echo "at $TC_TFTP_BOOT. No cleanup necessary..."
}

echo
echo "X2Go TCE cleanup is DONE."
echo
