#!/bin/bash

telnetconf="/etc/telnetd.conf"
service=telnetd

telnetd_status(){
	local pid=$(pidof -c $service)
	[ -z "$pid" ] && { 
		echo "$service stopped"
	} || {
		echo "$service running"
	}
}

telnetd_start(){
	[ ! -d /dev/pts ] && {
		mkdir -p /dev/pts                                                                                   
		mount -t devpts devpts /dev/pts
	}
	[ ! -d /tmp/TOS_CONFIG/zlog/ ] && mkdir -p /tmp/TOS_CONFIG/zlog/
	cp -a /etc/zlog/zlog_telnet.conf     /tmp/TOS_CONFIG/zlog/
	chmod 777 -R  /var/log/zlog/.

	local port="$(cat $telnetconf | awk '/port/ {print $2}')"
	if [ -z "$port" ];then
		port="-p 23"
	else
		port="-p $port"
	fi
	#echo port:$port

	local PID=$(pidof -c $service)
	[ -z "$PID" ] && {
		echo "telnetd starting"
		/usr/sbin/telnetd ${port} > /dev/null 2>&1
	} || {
		echo "telnetd running"
	}
}

telnetd_stop(){
	local pids=$(pidof -c $service)
	[ -z "$pids" ] && {
		echo "telnetd stopped"	
	} || {
		echo "telnetd stopping"
		kill -9 $pids
	}
}
case $1 in
   	start)
       	telnetd_start
		;;
    stop)
        telnetd_stop	
		;;
    restart)
        telnetd_stop	
        sleep 2
       	telnetd_start
		;;
    status)
       	telnetd_status
		;;
    *)      	
       	echo "Usage: $0 {start|stop|restart|status}"
		exit 1
		;;
esac
exit 0

