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

# GPL-3
cat << 'EEE' > /dev/null
/* b2rs, binary to radix string, od parse bourne-shell 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

# used below as reference
# https://qiita.com/richmikan@github/items/6b763519a28b4ce40031
# https://www.task-notes.com/entry/20150214/1423882800

# readlink portable. add $0 dir to path
# copy & paste to your script and ' rlp "$0" '. almost equals to ' readlink -f "$0" '
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"
}

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


#--- read_option
buf=`./rdopt "hxosrSN:" "$@"`
if [ $? -ne 0 ] ; then echo "$0: optErr. see -h. sleep." >/dev/stderr ;sleep 1000; exit 1; fi
eval "$buf"

# -d option omit. There is no demand for converting binary to decimal 
# ... and if use decimal, prefix 'n123' is more better than 'd123'
# 'd' char is used in hex expression '0x3d' etc. 
# re-entry N option. sed or other work needs line output. 

if [ "$opt_h" = '1' ] || [ $# -gt 1 ]; then
cat << 'EEE'
HowTo (b2rs, binary to radius string)
option: -h, -r(everse), -S(pace), -N(ewline),-x,o,s(hex, octal, backSlash)
------
ex.) ~$ printf 'abc' | b2rs (-o, dfl)
>>>	o141o142o143	...octal string at default

ex.) ~$ cat foo.bin |  b2rs -x -S	>>>	0x61 0x62 0x63	(add Space) 
ex.) ... b2rs -x -N '0x11'	>>>	0x3c0x11 (\n) 0xa1 ...	(add newline after 0x11) 
ex.) ... b2rs -s	>>>	\141\142\143	... printf '\141\142\143' >> abc

ex.) ~$ echo "abc" | b2rs -s (or x,o)  | b2rs -r	>> 'abc'
        printf '  0x610x62 \n \t o143' | b2rs -r	>> 'ab?..'	NG

'-r' make string/binary from 0x00/o000/\000 input. ignore space/tab/newline.
not allow mixed input. this pg works only at pipe input. (/dev/stdin)

------ speedtest
dd if=/dev/urandom bs=1000k count=1 > 1MB.buf
time cat 1MB.buf | tr -d '\n' > /dev/null	#...real/user/sys 12ms 8ms 4ms
time cat 1MB.buf | b2rs > /dev/null		#... 514ms 1484ms 56ms
time cat 1MB.buf | b2rs | b2rs -r > /dev/null		#... 1403ms 2292ms 192ms
time echo 'aaa' | b2rs > /dev/null		#... 40ms 0ms 4ms
EEE
exit 0
fi


#add -r. x,o,s ... auto detect.	sed... '&' is almost equals to '\1'.	sed -re '/^o/ s#(.)# \1#g'
if [ "$opt_r" = '1' ] ; then
 
tr '[:upper:]' '[lower]' | tr -d '\s\t\n' | 
tr 'xo\134' '\n' |
sed -ne '
/^0$/ b label2
:label1
n
p
b label1

:label2
n
$! {
	s/0$//
	p
	b label2
}
p' | 

awk '
NR == 1 {
	type="x"
	if(length($1) == 3){
		type="o"
	}
}

type == "x" {
#	nhex=substr($0, 1, 2)
	nhex="0x" $0
	printf("%c", nhex + 0)
	next
}

# type == "o"
{
	noct= 64 * substr($0, 1, 1) + 8 * substr($0, 2, 1) + substr($0, 3, 1)
	printf("%c", noct)
	next
}'

exit 0
fi

# awk can use binary output. %c is posix.
# %c ... http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap05.html
# echo | awk '{printf("%d",0x10)}'	>> not print 16. not 0x11 but "0x11" (d-quote)




#---------not -r

#--- main cmd 
#cmd="awk '{printf(\"$buf\", \$0)}'"

#newline option
nlcmd='cat -'
if [ "$opt_N" != "" ] ; then
	buf=`printf '%s' "$opt_N" | tr '[:upper:]' '[lower]' | 
		tr '\134' 'o' `	#...\012 == o012
	nlcmd="sed -e 's/$buf/&N/g'"
fi

#add space
sp=''
if [ "$opt_S" = "1" ] ; then
	sp=' '
fi

# '\' output
bscmd='cat -'
if [ "$opt_s" = '1' ] ; then
	bscmd="tr 'o' '\134'"
fi

# H,T ... head tail
if [ "$opt_x" = '1' ] ; then
	cmd="od -An -tx1 -w16 -v | sed -e 's# #""$sp""0x#g'"
else #o010, \010
	cmd="od -An -to1 -w16 -v | sed -e 's# #""$sp""o#g'"
fi

# update, w1 -> w16 speedup
# bottle neck ... od -tx1.
# od -An -tx1 -w32 -v  | tr ' ' '\n' | grep -v ^$ |
# sed -re 's/^/0x/g'  | eval "$cmd" | eval "$ncmd" | eval "$scmd" | 
# tr -d '\n' | tr 'S' ' ' | tr 'N' '\n' | grep -v '^$' | sed -re 's/[ ]$//g' | sed -re 's/^[ ]//g'


# w16 ... $cmd hardcode
eval "$cmd" | eval "$nlcmd" | tr -d '\n' | tr 'N' '\n' | 
sed -e 's/[ ]$//g' | sed -e 's/^[ ]//g' | eval "$bscmd"

#printf '%s\n' "$cmd"
#eval "$cmd" ; echo ""
exit 0
