#
# Manages SSH communications for cb
#
# $Id$
#
#
package CasparBuster::SSH;

use strict;
use Carp;
use ProjectBuilder::Base;

# Global vars
# Inherit from the "Exporter" module which handles exporting functions.
#
use vars qw($VERSION $REVISION @ISA @EXPORT);
use Exporter;
#
# Export, by default, all the functions into the namespace of
# any code which uses this module.

our @ISA = qw(Exporter);
our @EXPORT = qw(cb_ssh_init cb_ssh_close);

=pod

=head1 NAME

CasparBuster::SSH - module dealing with SSH for CasparBuster

=head1 DESCRIPTION

This modules provides functions to allow SSH communications in the CasparBuster environment

=head1 SYNOPSIS

  use CasparBuster::SSH;
  my $ssh = cb_ssh_init($remote,$machine);
  cb_ssh_close($ssh);

=head1 USAGE

=over 4

=item B<cb_ssh_init>

This function returns the SSH handle from Net::SSH2 after having created the object + authentification

The first parameter is the remote account name
The second parameter is the remote machine to connect to
The third parameter is the debug level

=cut

sub cb_ssh_init {

my $remote = shift;
my $machine = shift;
my $debug = shift || 0;
	
pb_log(1,"DEBUG: First time so we need to create the SSH::Net2 object\n");
my $ssh2 = Net::SSH2->new();
pb_log(3,"DEBUG: New SSH2 object created\n");
$ssh2->debug(1) if ($debug > 2);
pb_log(3,"DEBUG: SSH2 debug mode on\n") if ($debug > 2);

$ssh2->connect($machine) || confess "Unable to connect to $remote\@$machine: $!";
pb_log(3,"DEBUG: SSH2 connection done\n");

my $hdir = (getpwnam(getpwuid($<)))[7];
confess "Unable to connect to $remote\@$machine: $!" if (not $ssh2->auth_publickey($remote,"$hdir/.ssh/id_dsa.pub","$hdir/.ssh/id_dsa"));
pb_log(3,"DEBUG: SSH2 auth done\n");

my $chan = $ssh2->channel();
confess "Unable to create channel for $remote\@$machine: $!" if (not defined $chan);
pb_log(3,"DEBUG: SSH2 chan called\n");

$chan->exec("mkdir -p $ENV{'PBTMP'}");
pb_log(1,"DEBUG: Created $ENV{'PBTMP'} on $remote\@$machine\n");
$chan->close;

return($ssh2);
}

=over 4

=item B<cb_ssh_close>

This function closes properly the SSH comunication and remove the temp dir created remotely
The first parameter is the Net::SSH2 handle returned by cb_ssh_init

=cut


sub cb_ssh_close {

my $ssh2 = shift;

my $chan = $ssh2->channel();
confess "Unable to create channel $!" if (not defined $chan);
pb_log(3,"DEBUG: SSH2 chan called\n");

$chan->exec("rm -rf $ENV{'PBTMP'}");
pb_log(3,"DEBUG: Removing remotely $ENV{'PBTMP'}\n");
$chan->close();

$ssh2->disconnect();
}

1;
