#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 1999-2003 Mitel Networks Corporation
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 		
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 		
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
# 
# Technical support for this program is available from Mitel Networks 
# Please visit our web site www.mitel.com/sme/ for details.
#----------------------------------------------------------------------
package esmith;

use strict;
use Errno;

use esmith::ConfigDB;
use esmith::util;
use esmith::util::system qw(killall);


=head1 NAME

sshd-reload - starts or stops the ssh server based on your config

=head1 SYNOPSIS

  sshd-reload

=head1 DESCRIPTION

By looking at the value of sshd->status, sshd-reload will start (or
restart if its already running) your ssh server if its enabled.

If its disabled it will stop sshd with extreme prejudice.  All active
connections will be told to immediately disconnect.

If there's no status at all its a no-op.

=head1 FILES

  /var/lock/subsys/sshd

=begin testing

system( $^X, $Original_File );
is( $?, 0,  'ran myself ok' );
sleep 1;
my $last_touch = -M "/var/lock/subsys/sshd";
cmp_ok( $last_touch, '<', 0, 'sshd lockfile touched' );


# Test stopping the sshd using fake tests.
$ENV{ESMITH_CONFIG_DB} = 'e-smith-openssh/stop.conf';

# this will run 9 tests.
my $tb = Test::More->builder;
$tb->current_test($tb->current_test + 9);

system( $^X, '-Ie-smith-openssh/lib', '-Mreload_overrides', $Original_File );
is( $?, 0,  'ran myself ok' );


# Test when there's no status.
$ENV{ESMITH_CONFIG_DB} = 'e-smith-openssh/nostatus.conf';
system( $^X, $Original_File );
is( $?, 0,  'ran myself ok' );
cmp_ok( -M "/var/lock/subsys/sshd", '==', $last_touch, 
                                 'sshd lockfile untouched' );

=end testing

=cut

my $db = esmith::ConfigDB->open;
my $sshd = $db->get('sshd')             || exit 0;
my $status = $sshd->prop('status')      || exit 0;


my $action = ($status eq "enabled") ? "start" : "stop";

if ($action eq "start")
{
    if ( -f "/var/lock/subsys/sshd" )
    {
	$action = 'reload';
    }
}

esmith::util::serviceControl
(
    NAME   => 'sshd',
    ACTION => $action
) ||
  die "Couldn't $action sshd";


if ( $action eq 'stop' )
{
    killall('HUP', 'sshd') or warn("Could not stop sshd sessions\n");
}


exit (0);
