#!/usr/bin/env perl

use English;
use warnings;
use strict;

if ( $UID != 0 ) {
    print STDERR "Re-executing with sudo\n" if defined $ENV{VERBOSE};
    exec "sudo", "-n", "perl", "-T", $PROGRAM_NAME, @ARGV
}

$ENV{PATH} = "/usr/bin";

if ( @ARGV < 1 ) {
    print STDERR "usage $PROGRAM_NAME [PHEME_ID] {up|down|status}\n";
    exit 1
}

sub command {
    my ( $id, $cmd ) = @_;

    if ( $id =~ /(pheme)?([0-9][0-9])/ ) {
        my $name = "pheme$2";
        if ( $cmd =~ /(start|up|on)/ ) {
            print STDERR "$name up\n";
            system "/usr/bin/ipmitool", "-H", "$name-ipmi.lab", "-Pfoo", "-I", "lanplus", "power", "on";
            return 0;
        }
        elsif ( $cmd =~ /(stop|down|off)/ ) {
            print STDERR "$name down\n";
            my $r = system "/usr/bin/ssh", "-i", "/root/.ssh/id_rsa_phemecon_down", $name;
            if ( $r == 0 ) {
                print STDERR "Computer $name in use, not shutting down\n";
                return 1;
            }
            return 0;
        } elsif ( $cmd =~ /status/ ) {
            print STDERR "$name status ";
            system "/usr/bin/ipmitool", "-H", "$name-ipmi.lab", "-Pfoo", "-I", "lanplus", "power", "status";
            return 0;
        }
        print STDERR "unknown command $cmd\n";
        return 64;
    }
    print STDERR "invalid name $id\n";
    return 64;
}

if ( @ARGV == 1 ) {
    for my $i ( 1 .. 21 ) {
        command( sprintf( "%02d", $i ), $ARGV[0] )
    }
} else {
    exit command( $ARGV[0], $ARGV[1] )
}

