#!/usr/bin/perl
##
##  iLogin -- interactive login
##  Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
##

require "$ENV{HOME}/.ilogin";

use IPC::Open2;
open2(my $isel_out, my $isel_in, 'iselect', '-n', 'iLogin', '-t', 'Select Remote Host...', '-p3', '-K', '-kf');

%LOGINCMD = ();
%FTPCMD = ();
foreach $l (@CFG) {
    $area  = $l->{AREA};
    $hosts = $l->{HOSTS};
    print $isel_in "\n";
    print $isel_in "$area:\n";
    foreach $h (@{$hosts}) {
        $name   = $h->{NAME};
        $info   = $h->{INFO};
        $os     = $h->{OS};
        $type   = $h->{TYPE};
        $opt    = $h->{OPT};
        $passwd = $h->{PASSWD} || "$ENV{LOGIN}";
        $home   = $h->{HOME} || "/";
        if ($type eq 'ssh') {
            $cmd = "ssh $opt";
        }
        elsif ($type eq 'rlogin') {
            $cmd = "rlogin $opt";
        }
        elsif ($type eq 'expect') {
            $cmd = "expect -c 'set timeout 30'";
            foreach $c (@{$opt}) {
                $cmd .= " -c '".$c."'";
            }
        }
        $LOGINCMD{$name} = $cmd;

        ($login, $host) = ($name =~ m|^(.+)@(.+)$|);
        if ($login eq 'ftp' or $login eq 'anonymous') {
            $user = '';
        }
        else {
            $user = "$login:$passwd\@";
        }
        $FTPCMD{$name} = "cftp ftp://$user$host$home";

        print $isel_in sprintf("%-33s %-15s %-20s %6s <S:%s>\n", $name, $info, $os, $type, $name);
    }
}
close($isel_in);

$rc = <$isel_out>;
if ($rc ne '') {
   $rc =~ m|^(.+?):(.*)\n|;
   ($key, $name) = ($1, $2);
   if ($key eq 'RETURN' or $key eq 'KEY_RIGHT') {
       # Terminal Session
       print $LOGINCMD{$name}."\n";
   }
   elsif ($key eq 'f') {
       # FTP Session
       print $FTPCMD{$name}."\n";
   }
}
