#!/bin/bash

# **************************************************************************
# *                                                                        *
# *  FidoNMS v.0.3 by Alexey Khromov AKA zxalexis AKA 2:5030/723           *
# *                                                                        *
# **************************************************************************
# *                                                                        *
# * linkadd - add new link to Links, Passwords 	                           *
# * adding next to max if not the same address                             *
# *                                                                        *
# **************************************************************************

NMSBASE=""
FIDOBASE=""

if [ -f /etc/fidonms ]; then
    source /etc/fidonms
fi
if [ -z "$NMSBASE" ]; then
    #Try to guess
    NMSBASE=/opt/fidonms
fi
if [ -z "$FIDOBASE" ]; then
    FIDOBASE=/var/spool/ftn
fi


pwdsource=${BASH_SOURCE[0]}
while [ -L "$pwdsource" ]; do
        pwddir=$( cd -P "$( dirname "$pwdsource" )" > /dev/null 2>&1 && pwd )
        pwdsource=$( readlink "$pwdsource" )
        [[ $pwdsource != /* ]] && pwdsource=$pwddir/$pwdsource
done
pwddir=$( cd -P "$( dirname "$pwdsource" )" > /dev/null 2>&1 && pwd )


if [[ -f "${NMSBASE}/etc/links" ]]; then
        HPT_LINKS="${NMSBASE}/etc/links"
fi

if [[ -f "${NMSBASE}/etc/uplink" ]]; then
        HPT_UPLINK="${NMSBASE}/etc/uplink"
fi

if [[ -f "${NMSBASE}/etc/binkd.inc" ]]; then
        BINKD_LINKS="${NMSBASE}/etc/binkd.inc"
fi

if [ -f ${NMSBASE}/etc/bforce.passwd ]; then
    BFORCE_PASSWD=${NMSBASE}/etc/bforce.passwd
fi

if [ -f ${FIDOCONFIG} ];
then
    AKA=$(grep -ie ^Address ${FIDOCONFIG}| head -n1 | awk -F'[ @]' '{ print $2 }')
else
    echo "No FIDOCONFIG var found..."
    break;
fi

FCONFIG=${FIDOCONFIG}

# --------------------------------------------------------------------------
# Here comes a script
# --------------------------------------------------------------------------

declare -a larri=()	# Links array (aka aka aka)
declare -a lupli=()	# Links array for uplinks (aka)

declare -A larrs=()	# Links assoc array beg.line larrs[aka]=linenum
declare -A larre=()	# Links assoc array end line larre[aka]=linenum
declare -A larrn=()	# Links assoc array larrn[aka]=name
declare -A barrs=()	# Binkd assoc array barrs[aka]=linenum
declare -A farrs=()	# BForce assoc array farrs[aka]=linenum

if [[ -f ${HPT_UPLINK} ]]; then
	eline=$(cat "${HPT_UPLINK}"| wc -l)
	lnum=0
	loclink=0
	lname=""

	while read -r line; do
		if [[ "$(echo -ne ${line}| awk '{ print $1 }')" =~ ^[Ll][Ii][Nn][Kk]$ ]]; then
			if [ -n "$laka" ]; then
				elnum=$(( $lnum - 1 ))
				larre+=([${laka}]=${elnum})
			fi
			loclink=${lnum}
			lname=$(echo -ne ${line} | sed -e 's/[\t]/ /' | cut -d' ' -f 2-)
		fi
		if [[ "$(echo -ne ${line}| awk '{ print $1 }')" =~ ^[Aa][Kk][Aa]$ ]]; then
			laka=$(echo -ne ${line} | awk '{ print $2 }')
			lupli+=(${laka})
			larrs+=([${laka}]=${loclink})
			larrn+=([${laka}]=${lname})
		fi
		lnum=$(( ${lnum} + 1 ))
	done < ${HPT_UPLINK}
	larre+=([${laka}]=${eline})
fi

if [[ -f ${HPT_LINKS} ]]; then
	eline=$(cat "$HPT_LINKS" | wc -l )
	lnum=0
	laka=""
	elnum=0
	loclink=0
	lname=""
	
	while read -r line; do
		if [[ "$(echo -ne ${line}| awk '{ print $1 }')" =~ ^[Ll][Ii][Nn][Kk]$ ]]; then
			if [ -n "$laka" ]; then
				elnum=$(( $lnum - 1 ))
				larre+=([${laka}]=${elnum})
			fi
			loclink=${lnum}
			lname=$(echo -ne ${line} | sed -e 's/[\t]/ /' | cut -d' ' -f 2-)
		fi
		if [[ "$(echo -ne ${line}| awk '{print $1 }')" =~ ^[Aa][Kk][Aa]$ ]]; then
			laka=$(echo -ne ${line} | awk '{ print $2 }') 
			
			larri+=(${laka})
			larrs+=([${laka}]=${loclink})
			larrn+=([${laka}]=${lname})
		fi
		lnum=$(( ${lnum} + 1 ))
	done < ${HPT_LINKS}
	larre+=([${laka}]=$eline)
else
	errorlvl=2
fi

if [[ -f ${BINKD_LINKS} ]]; then
	lnum=0
	loclink=0
	# lpass=""
	# lmode=""

	while read -r line; do
		if [ -n "$line" ] && [[ ! "$line" =~ ^# ]]; then 
			# echo "$line"
			if [[ "$(echo -ne ${line}| awk '{ print $1 }')" =~ ^[Nn][Oo][Dd][Ee]$ ]]; then
				# echo "Pass line at ${lnum}"
				loclink="${lnum}"
				laka="$(echo -ne "${line}" | sed -e 's/[\t]/ /' | awk '{ print $2 }'| awk -F'@' '{ print $1 }')"
				# lpass="$(echo -ne "${line}" | sed -e 's/[\t]/ /' | awk '{ print $4 }')"
				# lmode="$(echo -ne "${line}" | sed -e 's/[\t]/ /' | awk '{ print $5 }')"
				# echo "Found pass line $lnum for $laka with password $lpass and mode $lmode"
				barrs+=([${laka}]=$loclink)
			fi
		fi
		lnum=$(( ${lnum} + 1 ))
	done < ${BINKD_LINKS}
else
	errorlvl=1
fi


echo "Main uplink array: ${lupli[0]}, location ${larrs[${lupli[0]}]} - ${larre[${lupli[0]}]},  name ${larrn[${lupli[0]}]}"

for link in ${larri[@]}; do
	echo "Links array [$link] = ${larrs[$link]}:${larre[$link]} , name ${larrn[$link]}, passline ${barrs[$link]}"
done

exit 10

# Initialize variables
cmdaka=""
cmdlg=""
cmdag=""
cmdpass=""
cmdyes=""

#TODO If no parameters - call interactive subroutine.

# Read parameters
while [ -n "$1" ]
do
	case "$1" in
		-a)	cmdaka="$2"
			shift;;
		-lg)	cmdlg="$2"
			shift;;
		-ag)	cmdag="$2"
			shift;;
		-pass)	cmdpass="$2"
			shift;;
		-y)	cmdyes="1";;
		*)	cmdusage="1";;
	esac
	shift
done

if [[ "${cmdusage}" = "1" ]]; then
	echo -ne "Usage: \n\
linkadd {-q} {-y} -a <aka> -pass <passwd> {-lg <linkgroup>} \n\
{-ag <accessgroup>}. If any of parameters absent - they are taken from default settings.\n"
	exit -2
fi

if [ -f ${BINKD_LINKS} ] && [ -f ${HPT_LINKS} ]; then
	
	if [ "${cmdaka}" != "" ]; then
		# Main adding procedure ---
		# begins here
		if [ "${cmdpass}" = "" ]; then
			cmdpass=${DefPassword}
		fi
		if [ "${cmdlg}" = "" ]; then
			cmdlg=${DefLinkGroup}
		fi
		if [ "${cmdag}" = "" ]; then
			cmdag=${DefAccessGroup}
		fi
		if [[ ${cmdyes} != 1 ]]; then
			echo "Add new Link ${cmdaka}: ${cmdpass} ? [y/n]"
			stty_old_cfg=$(stty -g)
			stty raw -echo ; answer=$(head -c 1) ; stty ${stty_old_cfg}
			if [[ "${answer}" != "${answer#[Yy]}" ]]; then
				echo "Adding link..."
			else
				exit -10
			fi
		fi

		# TODO: check for non-existance of link 
		# easier via larri[@]
		if [[ -f ${USERLIST} ]]; then
			exist=$(cat ${USERLIST}| sed -e '/^\s*#.*$/d' | awk -F',' '{ print $2 }'|grep ${cmdpnt}|wc -l)
		else
			exist=$(cat ${BINKD_PASSWD}| awk '{ print $1 }'|grep ${cmdaka}|wc -l)
		fi
		if [[ "${exist}" != "0" ]]; then
			echo "Point ${cmdaka} already exists!. Can not add another!"
			exit -1
		fi
		
		
		spnext=$(echo -ne "${spareline}" | awk -F'|' '{ print $4 }')
		if [[ "${cmdins}" != "1" ]] || [[ "${spnext}" = "0" ]]; then
			echo "Adding to end of file(s)"
			# TODO: check \n at end of file and add it
			echo -ne "${cmdaka}\t\t${cmdpass}\n" >> ${BINKD_PASSWD}

			if [ -n "$BFORCE_PASSWD" ]; then
				echo -e "password\t\t${cmdaka}\t\t${cmdpass}" >> ${BFORCE_PASSWD}
			fi

			# TODO: check \n at EOF
			# echo "\n" >> ${HPT_POINTS}
			echo -ne "Link $(echo -ne "${cmdstr}"| awk -F',' '{ print $2 }')\n" >> ${HPT_POINTS}
			echo "Aka ${cmdaka}" >> ${HPT_POINTS}
			echo "OurAka ${AKA}" >> ${HPT_POINTS}
			echo -e "Packer ${DefPacker}\nPassword ${cmdpass}" >> ${HPT_POINTS}
			echo -e "NetMailFlavour hold\nEchoMailFlavour hold\nFileEchoFlavour hold" >> ${HPT_POINTS}
			echo "packNetMail ${DefPackNetMail}" >> ${HPT_POINTS}
			echo "arcNetMail ${DefArcNetMail}" >> ${HPT_POINTS}
			echo "LinkGrp ${cmdlg}" >> ${HPT_POINTS}
			echo "AccessGrp ${cmdag}" >> ${HPT_POINTS}
			echo -e "\n" >> ${HPT_POINTS}

			# TODO check for \n in EOF
			if [[ -f "${USERLIST}" ]]; then
				echo "Point,${cmdstr}|${cmdpass}|${cmdlg}|${cmdag}" >> ${USERLIST}
			fi

		else
			# Adding in center of file(s)
			pindex=$(echo -ne "${spareline}"| awk -F'|' '{ print $5 }')
			cat ${BINKD_PASSWD} | sed -e "${pindex} a ""${cmdaka}\t\t${cmdpass}""" > ${BINKD_PASSWD}.new
			mv -f ${BINKD_PASSWD} ${BINKD_PASSWD}.old
			mv -f ${BINKD_PASSWD}.new ${BINKD_PASSWD}
			
			#TODO BFORCE password inj
			if [ -n "$BFORCE_PASSWD" ]; then
				bindex=$(echo -ne "${spareline}"| awk -F'|' '{ print $8 }')
				cat ${BFORCE_PASSWD} | sed -e "${bindex} a ""password\t\t${cmdaka}\t\t${cmdpass}""" > ${BFORCE_PASSWD}.new
				mv -f ${BFORCE_PASSWD} ${BFORCE_PASSWD}.old
				mv -f ${BFORCE_PASSWD}.new ${BFORCE_PASSWD}
			fi
			
			lindex=$(echo -ne "${spareline}"| awk -F'|' '{ print $6 }')
			lblock="Link $(echo -ne ${cmdstr}| awk -F',' '{ print $2 }')\n\
Aka ${cmdaka}\nOurAka ${AKA}\nPacker ${DefPacker}\nPassword ${cmdpass}\nNetMailFlavour hold\n\
EchoMailFlavour hold\nFileEchoFlavour hold\npackNetMail ${DefPackNetMail}\narcNetMail ${DefArcNetMail}\n\
LinkGrp ${cmdlg}\nAccessGrp ${cmdag}\n\n"
			cat ${HPT_POINTS} | sed -e "${lindex} a ""${lblock}""" > ${HPT_POINTS}.new
			mv -f ${HPT_POINTS} ${HPT_POINTS}.old
			mv -f ${HPT_POINTS}.new ${HPT_POINTS}

			if [[ -f ${USERLIST} ]]; then
				uindex=$(echo -ne "${spareline}"| awk -F'|' '{ print $7 }')
				ublock="Point,${cmdstr}|${cmdpass}|${cmdlg}|${cmdag}"
				cat ${USERLIST} | sed -e "${uindex} a ""${ublock}""" > ${USERLIST}.new
				mv -f ${USERLIST} ${USERLIST}.old
				mv -f ${USERLIST}.new ${USERLIST}
			fi

		fi
		if [[ ${sperr} = 1 ]] && [[ ${cmdyes} != 1 ]]; then
			echo "Your configs are not sorted (yet consistent).\n\
Would you like to sort it now? [y/n] "
			# TODO add choice and pointsort call
			old_stty_cfg=$(stty -g)
			stty raw -echo ; answer=$(head -c 1) ; stty ${old_stty_cfg}
			if [ "$answer" != "${answer#[Yy]}" ]; then
				sorting=1
				echo "Sorting..."
			else
				sorting=0
			fi
		fi
				
		if [[ ${sorting} = 1 ]] || [[ ${cmdyes} = 1 ]]; then
			$NMSBASE/bin/pointsort
			fi

	else
		echo "Can not add point without Point definition"
	fi
    
else
    echo "No userlists found! Aborting."
fi
