package ssh;

use warnings;
use strict;

use Net::OpenSSH;
use English;
use Data::Dump qw/dump/;
use client;
use CouchDB;

my $id = 2;

sub ethernet_bridge_to {
	my $host = shift;

	die "you need to run this as root\n" unless $UID == 0;

	warn "# reset local IP address";
	system "ifconfig virtual 172.16.10.$id";

	warn "# connect to $host";
	my $ssh = Net::OpenSSH->new( $host,
		master_opts => [ -w => "$id:$id", -o => 'Tunnel=ethernet' ],
	);

	foreach my $command ( "ifconfig tap$id up", "brctl addif virtual tap$id" ) {
		warn "# $command";
		system $command;
		$ssh->system( $command ) or die "$command ", $ssh->error;
	}

	warn "press enter to close tunnel to $host from $id";
	<STDIN>;

}

sub shell {
	my $ip = shift;

	my $ssh = Net::OpenSSH->new( $ip );

	my $html;
	my @shell;

	foreach my $command ( @_ ) {
		warn "root\@$ip:# $command\n";
		my ($out,$err) = $ssh->capture2( $command ) or die "$command ", $ssh->error;
		warn "$out\n$err";

		CouchDB::audit( $ip, $command, { ip => $ip, command => $command, out => $out, err => $err } );

		$html .= qq|<tt style="color: grey">root\@$ip:# <b>$command</b></tt><pre>$out</pre>|;
		$html .= qq|<pre style="color: red">$err</pre>| if $err;
	}

	return $html;
}

my $id_pub = '/root/.ssh/id_rsa.pub';

sub copy_id {
	my $ip = shift;
	my $ssh = client::ip_path( $ip, 'ssh' );
	return if -l $ssh;
	my $cmd = "sudo ssh-copy-id -i $id_pub root\@$ip";
	warn "# $cmd\n";
	system $cmd;
	symlink $id_pub, $ssh;
}

1;
