#!/bin/bash

# **************************************************************************
# *                                                                        *
# *  Pointtools v.0.2 by Alexey Khromov AKA zxalexis AKA 2:5030/722.143    *
# *                                                                        *
# **************************************************************************
# *                                                                        *
# * pointmod - modify Links, Passwords and Userlist files for point        *
# *     identified by aka (-a) or pointnum (-p)                            *
# *                                                                        *
# **************************************************************************

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

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


# Initialize variables
cmdaka=""
cmdpnt=""
cmdstr=""
cmdlname=""
cmdname=""
cmdcity=""
cmdtel=""
cmdflags=""
cmdlg=""
cmdag=""
cmdpass=""
cmdyes=""
cmdact=""

fixu=""
fixp=""
fixl=""

# Read parameters
while [ -n "$1" ]
do
        case "$1" in
                -f)	cfgfile="$2"
			shift;;
		-act)	cmdact="1";;
		-p)	cmdpnt="$2"
			shift;;
		-a)	cmdaka="$2"
			shift;;
		-s)     cmdstr="$2"
                        shift;;
		-ln)	cmdlname="$2"
			shift;;
		-nm)	cmdname="$2"
			shift;;
		-tel)	cmdtel="$2"
			shift;;
		-ct)	cmdcity="$2"
			shift;;
		-fl)	cmdflags="$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\
pointmod {-f cfgfile} {-y} [-p <pointnum>| -a <pointaka>] {-s <pointstr>} \n\
{-ln <linkname>} {-nm <Name>} {-ct <city>} {-tel <telephone>} {-fl <flags>}\n\
{-pass <passwd>} {-lg <linkgroup>} {-ag <accessgroup>} {-act}\n\
Pointnum or pointAKA is mandatory. -y supresses questions\n"
        exit -2
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 [[ -z ${cfgfile} ]]; then
        if [[ -f "${NMSBASE}/etc/pointcfg" ]]; then
                cfgfile="${NMSBASE}/etc/pointcfg"
        elif [[ -f "/etc/pointcfg" ]]; then
                cfgfile="/etc/pointcfg"
        elif [[ -f "$pwddir/etc/pointcfg" ]]; then
                cfgfile="$pwddir/etc/pointcfg"
        else
                echo "Config file not found. Please specify one"
                exit -2
        fi
fi

source ${cfgfile}

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}

if [ -f ${BINKD_PASSWD} ] && [ -f ${HPT_POINTS} ]; then
	if [[ "${cmdpnt}" != "" ]] && [[ "${cmdaka}" = "" ]]; then
                cmdaka=$(echo -ne "${AKA}.${cmdpnt}")
        elif [[ "${cmdaka}" != "" ]]; then
                cmdpnt=$(echo ${cmdaka}| awk -F'/' '{ print $2 }'| awk -F'.' '{ print $NF }')
        else
                echo "No valid parameters to locate points found! Use -a or -p switches!"
                exit -1
        fi

        # Searching for records in userlist:
        if [[ -f ${USERLIST} ]]; then
                uline=$(cat ${USERLIST}| grep -e "^Point,${cmdpnt}," -n| awk -F':' '{ print $1 }')
        fi
	
        
	# Searching for records in passwords:
        
	pline=$(cat ${BINKD_PASSWD} | grep -e "^${cmdaka}" -n | awk -F':' '{ print $1 }')
	
	if [[ -z ${uline} ]] && [[ -z ${pline} ]]; then
		echo "Point ${cmdpnt} not found. Nothing to do!"
		exit -1
	fi

        # Searching for records in links:
        lline=0
        llineend=0
        lidx=0
        lcnt=0
        lnext=0
        while read -r line; do
                lcnt=$(( ${lcnt} + 1 ))
                LLARG1=$(echo -ne ${line}| awk '{ print $1 }')
                LLARG2=$(echo -ne ${line}| awk '{ print $2 }')
                if [[ "${LLARG1}" =~ ^[Ll][Ii][Nn][Kk]$ ]]; then
                        if [[ ${lnext} = 1 ]]; then
                                llineend=$(( ${lcnt} - 1 ))
                                lnext=2
                        fi
                        lidx=${lcnt}
                fi
                if [[ "${LLARG1}" =~ ^[Aa][Kk][Aa]$ ]]; then
                        if [[ "${LLARG2}" = "${cmdaka}" ]]; then
                                lline=${lidx}
                                lnext=1
                        fi
                fi
                if [[ ${lnext} = 2 ]]; then
                        break
                fi

        done < ${HPT_POINTS}
        if [[ ${lnext} = 1 ]]; then
                llineend=${lcnt}
        fi

	if [[ -z "${uline}" ]] || [[ -z "${pline}" ]] || [[ ${lline} = 0 ]]; then
		echo "No valid point found!"
		exit -10
	fi


        # echo "Found uline: ${uline}, pline: ${pline}, lline: ${lline}-${llineend}"

	if [[ -f ${USERLIST} ]] && [[ -n "${uline}" ]]; then
		# echo "Making local uvars"
		ulines=$(cat ${USERLIST} | sed -ne "${uline} p")
		POINTLINE=$(echo -ne "${ulines}" | awk -F',' '{ print $1 }')
        	if [[ ${POINTLINE} =~ ^[Pp][Oo][Ii][Nn][Tt] ]]; then
            		POINT=$(echo ${ulines} | awk -F',' '{ print $2 }')
            		LNKNAME=$(echo ${ulines} | awk -F',' '{ print $3 }')
            		CITY=$(echo ${ulines} | awk -F',' '{ print $4 }')
            		NAME=$(echo ${ulines} | awk -F',' '{ print $5 }')
            		TEL=$(echo ${ulines} | awk -F',' '{ print $6 }')
            		FLAGS=$(echo ${ulines} | awk -F'|' '{ print $1 }' | cut -d, -f7-)
            		PSW=$(echo ${ulines} | awk -F'|' '{ print $2 }')
            		LNKGRP=$(echo ${ulines} | awk -F'|' '{ print $3 }')
            		ACCGRP=$(echo ${ulines} | awk -F'|' '{ print $4 }')
		fi
	
	fi
	plines=$(cat ${BINKD_PASSWD} | sed -ne "${pline} p")
	ppass=$(echo -ne "${plines}" | awk '{ print $2 }')
	if [[ -f ${USERLIST} ]]; then
		if [[ "${ppass}" != "${PSW}" ]]; then
			echo "Warning! Password differ!"
			# PSW=${ppass}
		fi
	else
		PSW="${ppass}"
	fi

	linksect=$(cat ${HPT_POINTS} | sed -ne "${lline},${llineend} p")

	while read -r line; do
		LLARG1=$(echo -ne "${line}" | awk '{ print $1 }')
		LLARG2=$(echo -ne "${line}" | awk '{ print $2 }')
		# echo "LLARG1: ${LLARG1}, LLARG2: ${LLARG2}"
		if [[ "${LLARG1}" =~ ^[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]$ ]]; then
			if [[ -f ${USERLIST} ]]; then
				if [[ "${PSW}" != "${LLARG2}" ]]; then
					echo "Warning! Passwords in HPT and BINKD do not match..."
				fi
			else
				PSW="${LLARG2}"
			fi
		elif [[ "${LLARG1}" =~ ^[Ll][Ii][Nn][Kk]$ ]]; then
			if [[ -f ${USERLIST} ]]; then
				if [[ "${LLARG2}" != "${LNKNAME}" ]]; then
					echo "Warning! Link names does not match."
				fi
			else
				LNKNAME="${LLARG2}"
			fi
		elif [[ "${LLARG1}" =~ ^[Ll][Ii][Nn][Kk][Gg][Rr][Pp]$ ]]; then
			if [[ -f ${USERLIST} ]]; then
				if [[ "${LLARG2}" != "${LNKGRP}" ]]; then
					echo "Warning! LinkGrp does not match."
				fi
			else
				LNKGRP="${LLARG2}"
			fi
		elif [[ "${LLARG1}" =~ ^[Aa][Cc][Cc][Ee][Ss][Ss][Gg][Rr][Pp]$ ]]; then
			if [[ -f ${USERLIST} ]]; then
				if [[ "${LLARG2}" != "${ACCGRP}" ]]; then
					echo "Warning! AccessGrp does not match."
				fi
			else
				ACCGRP="${LLARG2}"
			fi
		fi

	done < <(echo "${linksect}")

	# Now we have maximum base info to modify and write
	# Lets check for userstring mod

	if [[ -n ${cmdlname} ]] || [[ -n ${cmdtel} ]] || [[ -n ${cmdname} ]] || [[ -n ${cmdcity} ]] || [[ -n ${cmdflags} ]]; then

		if [[ -n ${cmdstr} ]]; then
			echo "Cannot modify part of pointstring and full simultaneously."
			exit -1
		fi
		if [[ -n ${cmdlname} ]]; then
			LNKNAME="${cmdlname}"
		fi
		if [[ -n ${cmdname} ]]; then
			NAME="${cmdname}"
		fi
		if [[ -n ${cmdcity} ]]; then
			CITY="${cmdcity}"
		fi
		if [[ -n ${cmdflags} ]]; then
			FLAGS="${cmdflags}"
		fi
		if [[ -n ${cmdtel} ]]; then
			TEL="${cmdtel}"
		fi

	fi
	
	if [[ -f ${USERLIST} ]]; then 
		fixu=1
		if [[ -z ${cmdstr} ]]; then
			cmdstr="Point,${POINT},${LNKNAME},${CITY},${NAME},${TEL},${FLAGS}"
		fi
	fi

	if [[ -n ${cmdpass} ]]; then
		if [[ -f ${USERLIST} ]]; then
			fixu=1
		fi
		PSW=${cmdpass}
		fixp=1
		fixl=1
	fi

	if [[ -n ${cmdlg} ]] || [[ -n ${cmdag} ]] || [[ -n ${cmdlname} ]]; then
		if [[ -f ${USERLIST} ]]; then
			fixu=1
		fi
		if [[ -n ${cmdlg} ]]; then
			LNKGRP=${cmdlg}
		fi
		if [[ -n ${cmdag} ]]; then
			ACCGRP=${cmdag}
		fi
		if [[ -n ${cmdlname} ]]; then
			LNKNAME=${cmdlname}
		fi
		fixl=1
	fi

	if [[ -z ${cmdyes} ]]; then
		if [[ -n ${fixu} ]] || [[ -n ${fixp} ]] || [[ -n ${fixl} ]]; then
			echo -e "Changes for point #${cmdpnt}:"
			if [[ -n ${fixu} ]]; then
				echo -e "\tPointstring: ${cmdstr}|${PSW}|${LNKGRP}|${ACCGRP}"
			fi
			if [[ -n ${fixp} ]]; then
				echo -e "\tPasswords file: ${cmdaka}\t${PSW}"
			fi
			if [[ -n ${fixl} ]]; then
				echo -e "\tLink: ${LNKNAME}, with LinkGrp: ${LNKGRP} and AccGrp: ${ACCGRP}"
			fi
		else
			echo "Nothing to do - exit"
			exit 0
		fi
		
		#ask for changes
		echo -e " --- Apply changes ? --- [y/n] "
		stty_old_cfg=$(stty -g)
		stty raw -echo ; answer=$(head -c 1) ; stty ${stty_old_cfg}
		if [[ "${answer}" != "${answer#[Yy]}" ]]; then
			echo "Making changes..."
		else
			exit -10
		fi
	fi
	# Making changes
	# we have these vars:
	#     uline - line of userlist to be modified when fixu==1
	#     pline - line of passwords to be modified when fixp==1
	#     lline..llineend - lines of links, when fixl==1
	if [[ -f ${USERLIST} ]]; then
		cat ${USERLIST} | sed -ne "1,$(( $uline - 1 )) p" > ${USERLIST}.new
		echo -e "${cmdstr}|${PSW}|${LNKGRP}|${ACCGRP}" >> ${USERLIST}.new
		cat ${USERLIST} | sed -ne "$(( $uline + 1 )),$ p" >> ${USERLIST}.new
	fi

	cat ${BINKD_PASSWD} | sed -ne "1,$(( $pline - 1 )) p" > ${BINKD_PASSWD}.new
	echo -e "${cmdaka}\t\t${PSW}" >> ${BINKD_PASSWD}.new
	cat ${BINKD_PASSWD} | sed -ne "$(( $pline + 1 )),$ p" >> ${BINKD_PASSWD}.new

	cat ${HPT_POINTS} | sed -ne "1,$(( $lline - 1 )) p" > ${HPT_POINTS}.new
	echo -e "Link ${LNKNAME}" >> ${HPT_POINTS}.new
        echo -e "Aka ${AKA}.${POINT}" >> ${HPT_POINTS}.new
        echo -e "OurAka ${AKA}" >> ${HPT_POINTS}.new
        echo -e "Packer ${DefPacker}" >> ${HPT_POINTS}.new
        echo -e "Password ${PSW}" >> ${HPT_POINTS}.new
        echo -e "NetMailFlavour hold" >> ${HPT_POINTS}.new
        echo -e "EchoMailFlavour hold" >> ${HPT_POINTS}.new
        echo -e "packNetMail ${DefPackNetMail}" >> ${HPT_POINTS}.new
        echo -e "arcNetMail ${DefArcNetMail}" >> ${HPT_POINTS}.new
        echo -e "LinkGrp ${LNKGRP}" >> ${HPT_POINTS}.new
        echo -e "AccessGrp ${ACCGRP}" >> ${HPT_POINTS}.new
        echo -e "\n" >> ${HPT_POINTS}.new
	cat ${HPT_POINTS} | sed -ne "$(( $llineend + 1 )),$ p" >> ${HPT_POINTS}.new
	

	if [[ -f ${USERLIST} ]]; then
		mv -f ${USERLIST} ${USERLIST}.old
		mv -f ${USERLIST}.new ${USERLIST}
	fi

	mv -f ${BINKD_PASSWD} ${BINKD_PASSWD}.old
	mv -f ${BINKD_PASSWD}.new ${BINKD_PASSWD}

	mv -f ${HPT_POINTS} ${HPT_POINTS}.old
	mv -f ${HPT_POINTS}.new ${HPT_POINTS}

fi
