#! /bin/bash
#
# This script runs telnet for LinPac
#

LPAPI='lpapi'

if [ $# -lt 1 ]; then
  echo 'Usage: telnet <host> [<port>]'
  exit 1
fi

# Test if LinPac is running
$LPAPI 0
if [ ! $? -eq 0 ]; then
  echo 'LinPac is not running'
  exit 1
fi

# Test if channel is free and mark it as private
if [ `$LPAPI $LPCHN state` -eq 0 ]; then
  $LPAPI $LPCHN do priv on
fi

# Switch terminal to ANSI mode
$LPAPI $LPCHN do term ansi

# Run telnet
telnet $1 $2

# Restore terminal settings
OLDTERM=`$LPAPI $LPCHN get STN_TERM`
if [ x${OLDTERM}x = xx ]; then
  $LPAPI $LPCHN do term none
else
  $LPAPI $LPCHN do term $OLDTERM
fi

# Switch private off
$LPAPI $LPCHN do priv off

echo
echo '*** Telnet session closed.'
