#!/bin/bash
#
# (c) 2019-2021 m-privacy GmbH
#
# Last change: ao, 05/Mar/2021
#

RED="\033[31;01m"
BLUE="\033[34;01m"
GREEN="\033[32;01m"
MAGENTA="\033[35;01m"
RESET="\033[00m"

MOUNTPOINT="/tmp/tgpromnt"

if test -z "$1"
then
	echo "Use: $0 number [mountpoint]"
	echo "Mount tgpro\$number image to mountpoint"
	echo "Default mountpoint is $MOUNTPOINT"
	echo "e.g.: $0 1"
	exit
fi

TGNUM="$1"
if test -n "$2"
then
	MOUNTPOINT="$2"
fi

case "$TGNUM" in
	[123456789])
		;;
	[123456789][0123456789])
		;;
	[123456789][0123456789][0123456789])
		;;
	*)
		echo -e "${RED}Number \"$TGNUM\" is not a number${RESET}"
		exit 1
esac

TMPFILE=/tmp/tgpro-image-mount.$$

if ! rbd ls | grep "^tgpro$TGNUM$"
then
	echo -e "${RED}Image tgpro$TGNUM does not exist${RESET}"
	exit 2
fi

if mount | grep -q "$MOUNTPOINT"
then
	echo -e "${RED}There is already something mounted to $MOUNTPOINT${RESET}"
	exit 3
fi

echo -e "${BLUE}Mount tgpro$TGNUM image to $MOUNTPOINT now${RESET}"
echo "Press return to continue or CTLR-C to abort"
read dummy

RBDDEV=$(rbd map "tgpro$TGNUM")
if test -z "$RBDDEV"
then
	echo -e "${RED}Failed to map image tgpro$TGNUM${RESET}"
	exit 4
fi

e2fsck -y -C 0 ${RBDDEV}p1
e2fsck -y -C 0 ${RBDDEV}p3
e2fsck -y -C 0 ${RBDDEV}p5
e2fsck -y -C 0 ${RBDDEV}p6

mkdir -p "$MOUNTPOINT"
timeout -k 5 10 mount -t ext4 -o discard ${RBDDEV}p1 "$MOUNTPOINT"
#mkdir -p "$MOUNTPOINT/var" "$MOUNTPOINT/home"
timeout -k 5 10 mount -t ext4 -o discard ${RBDDEV}p3 "$MOUNTPOINT/var"
#mkdir -p "$MOUNTPOINT/var/log"
timeout -k 5 10 mount -t ext4 -o discard ${RBDDEV}p5 "$MOUNTPOINT/var/log"
timeout -k 5 10 mount -t ext4 -o discard ${RBDDEV}p6 "$MOUNTPOINT/home"

echo -e "${BLUE}Ready.${RESET}"

exit 0
