#!/usr/bin/perl -w
# $Id: telnet_wrapper 1172 2019-06-29 07:27:24Z mueller $
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright 2009-2019 by Walter F.J. Mueller <W.F.J.Mueller@gsi.de>
#
#  Revision History:
# Date         Rev  Vers    Comment
# 2017-05-25   899   1.1    add 'r' --> reset and stty sane handling
# 2009-11-07   246   1.0    Initial version
#

use 5.14.0;                                 # require Perl 5.14 or higher
use strict;                                 # require strict checking

if (scalar(@ARGV) != 2) {
  print STDERR "usage: telnet_wrapper host port\n";
  exit 1;
}

my $host = $ARGV[0];
my $port = $ARGV[1];

print "$host $port\n";

my $telnet = `which telnet`;
chomp $telnet;

while(1) {
  my $rc = system $telnet, $host, $port;
  print STDERR "telnet failed with rc=$rc\n" if $rc != 0;
  print "enter q or <^D> to quit, r for tty reset, or <ENTER> to reconnect: ";

  my $buf = <STDIN>;
  unless ($buf) {                           # quit if EOF
    print "\n";
    exit 0;
  }
  chomp $buf;
  next    if $buf eq "";                    # <ENTER>
  exit 0  if $buf eq "q";                   # 'q'
  if ($buf eq "r") {                        # 'r'
    my $rc = system 'reset';
    print STDERR "'reset' failed with rc=$rc\n" if $rc != 0;
    $rc = system 'stty', 'sane';
    print STDERR "'stty sane' failed with rc=$rc\n" if $rc != 0;
  } else {
    print "Invalid input '$buf', only ^D,<ENTER> or 'r' allowed\n";
  }
}
