#!/bin/bash

CONF=/etc/ssh/sshd_config
INET=/etc/inetd.conf
SERV=/etc/services

# read settings
if [[ -a /boot/config/ident.cfg ]]; then
  source <(/usr/bin/fromdos < /boot/config/ident.cfg)
fi

# preset default values
[[ -z $BIND_MGT ]] && BIND_MGT=no
[[ -z $USE_TELNET ]] && USE_TELNET=yes
[[ -z $PORTTELNET ]] && PORTTELNET=23
[[ -z $USE_SSH ]] && USE_SSH=yes
[[ -z $PORTSSH ]] && PORTSSH=22
[[ -z $USE_UPNP ]] && USE_UPNP=no

# get management IP addresses
if [[ $BIND_MGT == yes ]]; then
  ETH=eth0
  [[ -e /sys/class/net/bond0 ]] && ETH=bond0
  [[ -e /sys/class/net/br0 ]] && ETH=br0
  IPV4=$(ip -4 addr show $ETH|awk '/inet /{gsub(/\/.+$/,"",$2);print $2;exit}')
  IPV6=$(ip -6 addr show $ETH noprefixroute|awk '/inet6 /{gsub(/\/.+$/,"",$2);print $2;exit}')
  [[ -z $IPV6 ]] && IPV6=$(ip -6 addr show $ETH scope global permanent|awk '/inet6 /{gsub(/\/.+$/,"",$2);print $2;exit}')
fi

# update SSH listening port
if [[ $PORTSSH == 22 ]]; then
  sed -ri 's/^#?Port [0-9]+$/#Port 22/' $CONF
else
  sed -ri "s/^#?Port [0-9]+\$/Port ${PORTSSH}/" $CONF
fi

# bind/unbind SSH service
if [[ -n $IPV4 ]]; then
  sed -ri "s/^#?(ListenAddress) 0.0.0.0\$/\1 ${IPV4}/" $CONF
else
  sed -ri 's/^#?(ListenAddress) [0-9]{1,3}\..+$/#\1 0.0.0.0/' $CONF
fi
if [[ -n $IPV6 ]]; then
  sed -ri "s/^#?(ListenAddress) ::\$/\1 ${IPV6}/" $CONF
else
  sed -ri 's/^#?(ListenAddress) [A-Fa-f0-9]{1,4}:.+$/#\1 ::/' $CONF
fi

# enable/disable SSH service
if [[ $USE_SSH == yes ]]; then
  if [[ -r /var/run/sshd.pid ]]; then
    /etc/rc.d/rc.sshd restart >/dev/null
  else
    /etc/rc.d/rc.sshd start >/dev/null
  fi
else
  /etc/rc.d/rc.sshd stop >/dev/null
fi

# enable/disable UPnP function
if [[ $USE_UPNP == yes ]]; then
  [[ ! -x /usr/bin/upnpc ]] && chmod +x /usr/bin/upnpc
else
  [[ -x /usr/bin/upnpc ]] && chmod -x /usr/bin/upnpc
fi

# update TELNET listening port
sed -ri "s/^(telnet\s+)[0-9]+\/(tcp|udp)\$/\1${PORTTELNET}\/\2/" $SERV

# bind/unbind TELNET service
if [[ -n $IPV4 ]]; then
  BIND="$IPV4:"
fi
# enable/disable TELNET service
if  [[ $USE_TELNET == yes ]]; then
  sed -ri "s/^#?(.+:)?(telnet\s.+telnetd\$)/${BIND}\2/" $INET
else
  sed -ri 's/^#?(.+:)?(telnet\s.+telnetd$)/#\2/' $INET
fi
/etc/rc.d/rc.inetd restart >/dev/null
