#!/usr/bin/perl

# This file is a part of RackTables, a datacenter and server room management
# framework. See accompanying file "COPYING" for the full copyright and
# licensing information.

use strict;
use Getopt::Long;

# fetch command-line parameters
my $op_help;
my $op_as_user;
GetOptions (
    'h' => \$op_help,
    'sudo-user:s' => \$op_as_user,
);
if ($op_help) {
    &display_help;
    exit;
}

&become_user;
exec ('ssh', @ARGV) or die "exec ssh: $!";

sub display_help {
    print <<END;
ssh batch client for RackTables.
Takes commands list in standard input and gives the responses via standard output.
Usage:
$0 [--as-user=<username>] [ -- ] [ ssh params ]
 --as-user            sudo self as specified username
END
}

sub become_user {
    if (defined $op_as_user) {
        my $uid = getpwnam ($op_as_user);
        if (! defined $uid) {
            die "getpwnam $op_as_user: $!";
        }
        if ($uid != $>) {
            exec ('sudo', '-u', "#$uid", $0, '--', @ARGV) or die "exec sudo: $!";
        }
    }
}
