#!/bin/bash
# Requires bash ≥4.
# ©2024 J. S. Gilstrap - All Rights Reserved.
# GPL ≥2.1 https://wwww.gnu.org

# Read Line Echo function. A Cat Here File without a system call.
RLE(){ local IFS=$'' ; while read line ; do echo "$line" ; done ; }

if [ -n "$1" ]
then
	ipv4=$1
elif [ -n "$REMOTE_ADDR" -a -z "$1" ]
then
	ipv4=$REMOTE_ADDR
elif [ -n "$TERM" ]
then
	while [ -z "$ipv4" ]
	do
		printf "Enter IPv4 Address : "
		read ipv4		
	done
else
	exit 1
fi

c=4 ; ip=0
for o in ${ipv4//./ }
do
	case $c in
		4) o=$(($o*16777216)) ;;
		3) o=$(($o*65536)) ;;
		2) o=$(($o*256)) ;;
		1) o=$o ;;
		*) break ;;
	esac
	ip=$(($ip+$o))
	((c--))
done

if [ -n "$REMOTE_ADDR" ]
then

RLE << EoF
Content-type: text/plain ; charset="utf-8"

IPv4: $ipv4
Decimal: $ip

If you want to use another address other that yours then use it as an
argument like this: http://www.example.org/cgi-bin/ipv42dec?A.B.C.D
EoF

elif [ "$2" = -d ]
then
	printf "$ip\n"
else

RLE << EoF
   IPv4: $ipv4
Decimal: $ip

If decimal only is desired then
use the -d switch as argument 2,
Ex: ipv42dec A.B.C.D -d
EoF

fi

