#!/bin/bash
#/split_string.sh
# LOF ROF LOL LOF BWO

# parse the command line for the arguments OPERATION, SEP, (SEP2 optional) and  PARSESTRING
# sh ./split_string.sh BW / . /usr/name_d/tar.gz
if [[ $4 ]] ; then
 OPERATION=$1
 SEP=$2
 SEP2=$3
 shift 3
elif [[ $3 ]] ; then
 OPERATION=$1
 SEP=$2
 SEP2=$2
 shift 2
else
 echo "3 arguments are needed"
 exit
fi
# the rest of the command line is the string we are to parse
PARSESTRING="$@"

has_char() {
	case $2 in *$1*) true ;; *) exit 1 ;; esac
}

	# has_char $SEP $PARSESTRING && has_char $SEP2 $PARSESTRING && echo yes
	
	case $PARSESTRING in
		*$SEP*)
			# echo "found SEP"
			case $PARSESTRING in
				*$SEP2*) true ;;
				*) 
				# echo "SEP2 not found"
				exit 1 ;;
			esac
		;;
		*) 
		# echo "SEP not found" 
		exit 1
		;;
	esac
	
	case $OPERATION in
		LOF) [[ ${PARSESTRING%%$SEP*} != "" ]] && echo ${PARSESTRING%%$SEP*} || exit 1 ;;
		LOL) [[ ${PARSESTRING%$SEP*} != "" ]] && echo ${PARSESTRING%$SEP*} || exit 1 ;;
		ROF) [[ ${PARSESTRING#*$SEP} != "" ]] && echo ${PARSESTRING#*$SEP} || exit 1 ;;
		ROL) [[ ${PARSESTRING##*$SEP} != "" ]] && echo ${PARSESTRING##*$SEP} || exit 1 ;;
		SL) [[ ${PARSESTRING%%$SEP*} = "" ]] && echo ${PARSESTRING#$SEP*} || exit 1 ;;
		ST) [[ ${PARSESTRING##*$SEP} = "" ]] && echo ${PARSESTRING%$SEP} || exit 1 ;;
	esac
	case $OPERATION in
		BWO) 	
			#echo $SEP $SEP2 $PARSESTRING
			# strip the leading char if it is the same as SEP -mostly for ignoring leading slashes
			[[ ${PARSESTRING%%$SEP*} = "" ]] && echo PARSESTRING=${PARSESTRING#$SEP*}
			# get the string to the right of the first separator 
			ROF=${PARSESTRING#*$SEP}
			#echo ROF=$ROF
			# get the string to the left of last separator (SEP2 if given) from the reslut above
			LOL=${ROF%$SEP2*}
			#echo LOL=$LOL
			if [[ $ROF = $LOL ]] ; then
			 # if there is only one instance of a single named separator
			 # or if one of the named separators is not found error status is 1
			 exit 1
			else
			 echo LOL=$LOL
			fi
		;;
		HAS)
			#SEP2=$PARSESTRING
			has_char $SEP $PARSESTRING
	esac
