#!/usr/bin/perl
use FileHandle;
use IPC::Open2;

sub establish_trust {
  my ($remoteuser, $remote) = @_;

  # RSA key of THIS machine
  my $hostname = `hostname -f`;
  $hostname =~ /([a-zA-Z0-9._-]*)/; $hostname = $1;
  my $rsalocal = `cat /etc/ssh/ssh_host_rsa_key.pub | sed 's/\\([^=]*==*\\) .*/$hostname \\1/'`;
  $rsalocal =~ /(.*)/; $rsalocal = $1;

  # generate key pair for local user
  # (who will be the trusted user on the REMOTE machine)
  my $HOME = `echo \$HOME`;
  $HOME =~ /(.*)/; $HOME = $1;
  if (! -d "$HOME/.ssh") {
    mkdir ("$HOME/.ssh", 0700);
  }
  if ((! -e "$HOME/.ssh/id_rsa") || (! -e "$HOME/.ssh/id_rsa.pub")) {
    `ssh-keygen -b 2048 -t rsa -N "" -f \$HOME/.ssh/id_rsa`;
  }
  my $rsauser = `cat \$HOME/.ssh/id_rsa.pub`;
  $rsauser =~ /(.*)/; $rsauser = $1;
  $rsauser =~ /.* ([^ ]*)$/;
  my $rsaid = $1;

  # open connection; prompt for password and host authenticity, if trust
  # is not already established
  $pid = open2(*R, *W, "ssh -l $remoteuser $remote" );

  # add host and user public RSA key to the appropriate files
  print W qq|if [ ! -d "\$HOME/.ssh" ]; |
	  . qq|then mkdir -m 700 "\$HOME/.ssh"; |
	  . qq|fi\n|;
  print W qq|if grep $hostname \$HOME/.ssh/known_hosts > /dev/null 2>&1; |
	  . qq|then echo "Host already known"; else cat << "EOF" |
	  . qq|>> \$HOME/.ssh/known_hosts\n$rsalocal\nEOF\n|
	  . qq|fi\n|;
  print W qq|if grep $rsaid \$HOME/.ssh/authorized_keys > /dev/null 2>&1; |
	  . qq|then echo "User already known"; else cat << "EOF" |
	  . qq|>> \$HOME/.ssh/authorized_keys\n$rsauser\nEOF\n|
	  . qq|fi\n|;
  print W qq|chmod 600 \$HOME/.ssh/*\n|;
  print W "exit\n";
  while ($got = <R>) {
    print ":: $got";
  }
}

&establish_trust ("root", "atlantis.mylinuxproject.de");

