#!/bin/bash

#  NOTE: 2.6 VERSION ONLY!!!!

# ftpports
# script to:
# 1) parse or change the -p option from the xinetd conf file for pure-ftpd
# Some systems may not have it set, so this will also set/display.  
# 2) display or set the cmd ftp port.
# 
# NOTE ON INSTALLATION!!!
# This script should have two symlinks to it is the same directory.
# This is part of the logic of the script.
# ftpdataport -> ftpport
# ftpcomport  -> ftpport
#
# 
# Mike Goins
# Adtec Digital
# Oct 13, 2006
#

# sanity version check
if [ ! -e /usr/sbin/xinetd ]; then exit 10; fi


CONF_FILE="/etc/xinetd.d/ftp"
SERVICES_FILE="/etc/services"
DEFAULT_LOW=1024
DEFAULT_HIGH=65535
RESTART_CMD="/etc/init.d/xinetd restart"

SCRIPT=${0##*/}


function get_ftpcmdport ()
{
   # $1 services file
   FTP_LINE=$(grep "^ftp[[:space:]]" $1)
   CMD_PORT=$(expr "$FTP_LINE" : "ftp[[:space:]]*\([0-9]*\)\/tcp")
   echo $CMD_PORT
}

function set_ftpcmdport ()
{
   # $1 file, $2 is the new port
   vi -e -n -c "%s/\(^ftp[[:space:]]\{1,\}\)[0-9]*\(\/tcp$\)/\1${2}\2/ | wq" $1 &>/dev/null
   $RESTART_CMD &>/dev/null
}


function get_ftpdataport ()
{
   FTP_CONF=$(grep ^[^#].*server_args $1)
   PORT_LOW=$(expr "$FTP_CONF" : ".*-p\([0-9]*\):.*")
   PORT_HI=$(expr "$FTP_CONF" : ".*-p[0-9]*:\([0-9]*\).*")
   echo "${PORT_LOW} ${PORT_HI}"                 # show the setting
}

function set_ftpdataport ()
{
   # $2 low $3 high , $1 conf file
   #parse the args
   LO=$2
   HI=$3 
   
   if [ $LO -gt 1024 -a $HI -lt 65536 ]; then
      DATA_RANGE="${LO}:${HI}"
   else
      exit 2
   fi
   sed -i -e "/^[^#] *server_args/s/\(-p\)[0-9]*:[0-9]*/\1${DATA_RANGE}/" $CONF_FILE
   $RESTART_CMD &>/dev/null  
}

if [ "$SCRIPT" == "ftpdataport" ]; then
	 
   if [ $# -eq 0 ]; then
      get_ftpdataport "$CONF_FILE"
   elif [ $# -eq 2 ]; then 
     set_ftpdataport "$CONF_FILE" "$1" "$2"
   else
     exit 2
  fi
elif [ "$SCRIPT" == "ftpcmdport" ]; then
   if [ $# -eq 0 ]; then
      get_ftpcmdport "$SERVICES_FILE"
   elif [ $# -eq 1 ]; then 
     set_ftpcmdport "$SERVICES_FILE" "$1" 
   else
     exit 2
  fi
else
  exit 2
fi     
