#!/bin/bash
################################################################################
# remember: chmod u+x makedir.sh
################################################################################
# arguments: wrkdir dir backup
################################################################################
# set working directory
wrkdir=$1
# set directory to make
dir=$2
# set backup check indicator
backup=$3
################################################################################
# set makedir indicator to no as default
makedir="n"
# check if 'dir' output folder exists
if [ -d $wrkdir/$dir ]; then
	# 'dir' output folder does exist
	if [ $backup -eq 1 ]; then
		# check if 'dir' output folder is empty
		if [ ! "$(ls -A $wrkdir/$dir 2> /dev/null)" == "" ]; then
			# check if existing output files must be backed up
			read -p "'$dir' output folder not empty... backup folder (y/n)? "
			if [[ "$REPLY" =~ ^(y|yes|Y|YES|Yes)$ ]]; then
				# determine the number of the backup
#				nr=$(find . -name $wrkdir/$dir.\* | wc -l)
				nr=$(find . -wholename $wrkdir/$dir.\* | wc -l)
				# backup existing folder
				mv $wrkdir/$dir $wrkdir/$dir.$nr
				# set makedir indicator to yes
				makedir="y"
			else
				read -p "remove existing files (y/n)? "
				if [[ "$REPLY" =~ ^(y|yes|Y|YES|Yes)$ ]]; then
					rm $wrkdir/$dir/*
					echo "removed existing files from '$dir' output folder..."
				fi
			fi
		fi
	fi
else
	# set makedir indicator to yes
	makedir="y"
fi
# check if makedir indicator is yes
if [ "$makedir" == "y" ]; then
	# make 'dir' output folder
    mkdir $wrkdir/$dir
	echo "created new '$dir' output folder..."
fi
################################################################################
