#!/bin/bash

function check_sock_ph()
{
	if [ $# -eq 2 ];then
		XPATH=$1
		RPATH=$2

		SF=${XPATH}${RPATH}

		if [ -d "$XPATH" ]; then
			if [ -S $SF ]; then
				echo -e "OK MNT\t $SF"
			elif [ -f $SF ]; then
				echo -e "OK\t $SF"
			elif [ -d $SF ]; then
				echo -e "WARNING\t $SF"
				echo -e "\t is a dir, replacing with a file"
				rmdir $SF
				touch $SF
				echo -e "\t placeholder created."
			elif ! [ -e $SF ]; then
				echo -e "WARNING\t $SF"
				echo -e "\t doesn't exist"
				RPD=`dirname ${RPATH}`
				if ! [ -d ${XPATH}${RPD} ]; then
					echo -e "\t parent dir doesn't exist"
					mkdir -p ${XPATH}${RPD}
					echo -e "\t parent dir created."
					touch $SF
					echo -e "\t placeholder created."
				else
					touch $SF
					echo -e "\t placeholder created."
				fi
			else
				echo -e "ERROR\t $SF exists but is a special type."
			fi
		else
			echo -e "ERROR\t $SF: ${XPATH} doesn't exist"
		fi
	fi
}

function check_phdir()
{
	if [ $# -eq 2 ];then
		XPATH=$1
		RPATH=$2

		SF=${XPATH}${RPATH}

		if [ -d "$XPATH" ]; then
			if [ -d $SF ]; then
				echo -e "OK\t $SF"
			elif ! [ -e $SF ]; then
				echo -e "WARNING\t $SF"
				echo -e "\t doesn't exist"
				mkdir -p ${XPATH}${RPATH}
				echo -e "\t dir created."
			else
				echo -e "ERROR\t $SF exists but not a dir."
			fi
		else
			echo -e "ERROR\t $SF: ${XPATH} doesn't exist"
		fi
	fi
}

# start
if [ $# -eq 3 ];then
	XPATH=$1
	RPATH=$2
	FOD=$3

	if [ "$FOD" == "file" ]; then
		check_sock_ph $XPATH $RPATH
	elif [ "$FOD" == "dir" ]; then
		check_phdir $XPATH $RPATH
	fi
else
	echo "Usage: $0 existing_dir relative_path file|dir"
	echo "Example 1: ... /chroot/example/run /systemd/journal/dev-log file"
	echo "Example 2: ... /chroot/example/run /systemd dir"
fi

exit 0

