#!/bin/sh
# platform ... GNU/debian dash 

cat << 'EEE' > /dev/null
/* ssp ....shortest / longest match parser. bourne-sh script
 * Copyright (C) 2017,2018 Momi-g
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
EEE

# 2-clause BSD license
# https://sites.google.com/site/jdisnard/realpath
cat << 'EEE' > /dev/null
/* Copyright 2010 Jon Disnard. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 * 
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY Jon Disnard ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Jon Disnard.
 */
EEE

rlp() {
	cdir=`pwd`
	pdir=`cd .. ; pwd`

	inname="$*"		# not $@ but $*
	ck=${inname%%/*}
	if [ "$ck" = '' ] ; then
		fullname="$inname"
	elif [ "$ck" = '..' ] ; then
		buf=`printf '%s' "$inname"`
		fullname="$pdir"'/'${buf#*/} 
	else	# ./aaa.txt  or   aaa.txt
		buf=`printf '%s' "$inname"`
		fullname="$cdir"'/'${buf#*/}
	fi
	
# https://sites.google.com/site/jdisnard/realpath
 	# Dereference symbolic links.

	if [ -h "$fullname" ] && [ -x "/bin/ls" ] ; then
		base=`/bin/ls -l "$fullname" `
		count=`/bin/ls -lL "$fullname" | tr -c -- '>-' ' ' |
			sed -e 's/->/@/g' | tr -d -c '@' | wc -c`	# check '->' string(filename, username etc)
		count=$((count+1))
		for ii in `seq 1 $count `
		do
			base=${base#*->}
		done
			fullname='/'"${base#*/}"	# remove head ' '
	fi
	printf '%s' "$fullname"
	
# if ypu need octal ...	
# 	printf '%s' "$fullname" | od -An -to1 -w16 -v | tr -d '\n' |
#		sed -e 's# 000#@#g' | tr ' ' '\134' | tr '@' '\n'
}

fullname=`rlp "$0" `
fulldir=`dirname "$fullname"`
buf=`echo "$fulldir" | tr -d -c ':'`
if [ "$buf" = "" ] ;then
	PATH="$fulldir"":$PATH"
else
	echo "$0: warning. fullpath includes ':'. skip add $fpath to \$PATH." >/dev/stderr
fi
cd "$fulldir"

buf=`./rdopt ":f:b:hg" "$@"`
if [ $? -ne 0 ] ; then
	echo "$0: opt err. see -h. sleep 1000." > /dev/stderr
	sleep 1000
	exit 1
fi
eval "$buf"
#printf "%s\n" "$@"


if [ "$opt_h" != "" ] || [ $# -eq 0 ] ; then
cat << 'EEE'
HowTo (Split and Swap then Print, ssp)
option: -h(elp), -f(orward), -b(ack), -g(ignored opt)
------
ex.) ~$ echo 'aaa/123:foo/_bar' | ssp -fs '*/' 2
   ... aaa/   123:foo/_bar    ...split using 'f'orward 's'hortest match
      1          2
   ... then print no.2
   >> 123:foo/_bar		...if no_match, 1 is empty

ex.) ~$ echo 'aaa/123:foo/_bar' | ssp -b l -- 'a/*' 031 'foo3' 
   ... aa   a/123:foo/_bar    ...split using 'b'ackward 'l'ongest match
        1        2
   ... then print no.0,3,1.   0:base string   3 or later:passed args
   >>> aaa/123:foo/_bar + foo3 + aa

-f, -b: forward, backward. they have subArgs 's'hort or 'l'ong.
*ab: sh ptn. not'sed reg'. *:wildcard, ?:anyOneChar, \:esc. see 'man sh'.
01234-: print sequence. 0:base, 1:front str, 2:back str, 3-:passed args

input '--'(opt end) if you want to avoid parsor troubles.
support only stdin/stdout.
EEE
exit 0
fi

#http://www.itmedia.co.jp/enterprise/articles/0901/06/news074.html
ptn="$1"

#printf "ooo%s" "$@"
#literal safe
#ptn=`getopt -s sh -q -o "" -- "$ptn" | cut -b 5-`	#get quated string

nums="$2"
buf=`echo $2 | awk '$0~/^[0123456789]+$/{print $0}'`
if [ -z $buf ] ; then
	echo "$0: args err. \$2 has only num char. sleep." > /dev/stderr
	sleep 1000
	exit 1
fi

if [ "$opt_f" = "" ] && [ "$opt_b" = "" ] ; then
	echo "$0: opt err. select one option '-f' or '-b'. sleep" > /dev/stderr
	sleep 1000
	exit 1
fi


#main---

#tmp3="$3"... save insert args
for i in `seq 3 $#`
do
	#arg=`eval echo '$'$OPTIND`
	eval tmp$i=\"\$$i\"
	#eval "echo \"\$tmp$i\""
done

while read -r A
do
#front short match

if [ "$opt_f" = "s" ] ; then
	tmp0="$A"
	tmp2=${A#${ptn}}
	if [ "$tmp2" = "$tmp0" ] ; then		#no match
		tmp1=''
		tmp2="$tmp0"
	else
	buf=`printf "%s" "$tmp2" | wc -c`
	buf1=`printf "%s" "$tmp0" | wc -c`
	buf=`expr $buf1 - $buf`
	tmp1=`printf "%s" "$A" | cut -b -"$buf"`
	fi
	
#front long match
elif [ "$opt_f" = "l" ] ; then
	tmp0="$A"
	tmp2=${A##$ptn}
	if [ "$tmp2" = "$tmp0" ] ; then		#no match
		tmp1=''
		tmp2="$tmp0"
	else
	buf=`printf "%s" "$tmp2" | wc -c`
	buf1=`printf "%s" "$tmp0" | wc -c`
	buf=`expr $buf1 - $buf`
	tmp1=`printf "%s" "$A" | cut -b -"$buf"`
	fi
	
#back short match
elif [ "$opt_b" = "s" ] ; then
	tmp0="$A"
	tmp1=${A%$ptn}
	if [ "$tmp1" = "$tmp0" ] ; then		#no match
		tmp2=''
		tmp1="$tmp0"
	else
	buf=`printf "%s" "$tmp1" | wc -c`
	#buf1=`printf "%s" "$tmp0" | wc -c`
	buf=`expr $buf + 1`
	tmp2=`printf "%s" "$A" | cut -b "$buf"-`
	fi

#back long match
elif [ "$opt_b" = "l" ] ; then
	tmp0="$A"
	tmp1=${A%%$ptn}
	if [ "$tmp1" = "$tmp0" ] ; then		#no match
		tmp2=''
		tmp1="$tmp0"
	else
	buf=`printf "%s" "$tmp1" | wc -c`
	#buf1=`printf "%s" "$tmp0" | wc -c`
	buf=`expr $buf + 1`
	tmp2=`printf "%s" "$A" | cut -b "$buf"-`
	fi
	
else
	echo "ssp, err. see -h" > /dev/stderr
	exit 1
fi

#combine strings
#echo $nums
	
nums="$2"
num=`printf "%s" $nums | wc -m`

out=''
#echo "$buf"
for i in `seq 1 $num` ; do
buf=`printf "%s" "$nums" | cut -b 1`	#031..  buf='0' ...31
#echo $buf
out="$out"'${'"tmp$buf"'}'		# ${tmp3}${tmp0}${tmp1} ...
#echo $out
nums=`printf "%s" "$nums" | cut -b 2-`
done
eval 'printf "%s\n" "'"$out"'"'	#printf "%s\n" "${tmp3}${tmp0}${tmp1}"

done	#while read end
