#!/bin/bash
### BEGIN INIT INFO
# Provides:          coredumps_folder
# Required-Start:
# Required-Stop:
# Default-Start:     2 3
# Default-Stop:
# Short-Description: Mount coredumps.fs to /coredumps
### END INIT INFO

. /etc/default/crypta-coredumps-config

# script for automate mount of loop device with
# resource files
ENV="env -i LANG=C PATH=/bin:/usr/bin"

. /lib/lsb/init-functions

make_image ()
{
	local RES_IMG="$1"
	local SIZE="$2"
	echo "Creating loop device and formating partition.."
	rm -f "$RES_IMG"
	dd if=/dev/zero of="$RES_IMG" bs=1M count=0 seek="$SIZE"
	mkfs.ext2 -q -F "$RES_IMG"
	tune2fs -m0 "$RES_IMG"
}

case "$1" in
	start)
		SIZE="${2:-$SIZE}"
		if ! [ -f "$RES_IMG" ]
		then
			make_image "$RES_IMG" "$SIZE"
		fi

		if ! [ -e  "$MOUNTP" ]; then
		    mkdir -p "$MOUNTP"
		fi

		if [ -f "$RES_IMG" ] && [ -d "$MOUNTP" ]; then
			# check if coredumps is already mounted
			mountpoint -q "${MOUNTP}" && {
				log_failure_msg "/coredumps is already mounted"
				log_end_msg 1
				exit 1;
			}

			# check if resources already mounted
			mount | grep -q "$RES_IMG" && {
				log_failure_msg "$RES_IMG is already mounted"
				log_end_msg 1
				exit 1;
			}

			ACTUAL_SIZE="$(( $(stat -c%s "$RES_IMG")/1024/1024 ))"
			if [ "${SIZE}" -gt "${ACTUAL_SIZE}" ]
			then
				echo "Need resize ${ACTUAL_SIZE}M -> ${SIZE}M"
				make_image "$RES_IMG" "$SIZE"
			fi

			echo "Mounting resouse img file"
			mount -o loop,noatime -t ext2 $RES_IMG $MOUNTP || {
				log_failure_msg "Mounting $RES_IMG to $MOUNTP failed"
				log_end_msg 1
				exit 1;
			}
			if ! [ -d "$MOUNTP/lost+found" ]
			then
				cd $MOUNTP
				mklost+found || {
					log_failure_msg "Creating lost+found failed"
					log_end_msg 1
					exit 1
				}
				cd -
			fi

			chmod 1777 $MOUNTP

			# update sysctl.conf
			if ! egrep -q '^ *kernel.core_pattern' /etc/sysctl.conf; then
				echo "kernel.core_pattern = /coredumps/%e.%t.%p.core" >> /etc/sysctl.conf
			fi
			if ! egrep -q '^ *kernel.core_uses_pid' /etc/sysctl.conf; then
				echo "kernel.core_uses_pid = 1" >> /etc/sysctl.conf
			fi
			echo "Runing sysctl -p -q"
			sysctl -q -p || {
				echo "Error occured while loading sysctl.conf"
				exit 1
			}
		else
			echo "File $RES_IMG or directory $MOUNTP doesn't exits"
			exit 1;
		fi
		log_end_msg $?
	;;

	stop)
		log_begin_msg "Umounting $RES_IMG from $MOUNTP.."
		umount $RES_IMG
		log_end_msg $?
	;;

	*)
		echo "Usage: $0 {start|stop}"
		exit 1
	;;
esac

exit 0
