#!/usr/bin/perl 

#
# nethserver-ibays-set-password -- change the ibay password with htpasswd
#

#
# Copyright (C) 2012 Nethesis S.r.l.
# http://www.nethesis.it - support@nethesis.it
# 
# This script is part of NethServer.
# 
# NethServer 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 3 of the License,
# or any later version.
# 
# NethServer 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 NethServer.  If not, see <http://www.gnu.org/licenses/>.
#

use strict;
use esmith::ConfigDB;


my $eventName = shift || die('Missing event name argument!');
my $givenVHost = shift;

my $htpasswd = '/usr/bin/htpasswd';
my $passwordFile = '/etc/httpd/conf/basic.htpasswd';
my $errors = 0;

if ( ! -x $htpasswd ) {
    # If htpasswd executable is missing quit here.
    exit 0;
}

my $db = esmith::ConfigDB->open_ro('vhosts') || die("Can't open vhosts db");
my @vhosts = $givenVHost ? ($db->get($givenVHost)) : $db->get_all_by_prop('type'=>'vhost');

foreach my $vhostRecord (@vhosts) {

    my $vhostName = $vhostRecord->key;

    # Skip if no password is required
    if($vhostRecord->prop('PasswordStatus') ne 'enabled') {
	next;
    }

    my $password = $vhostRecord->prop('PasswordValue');

    # Error, if no passowd is set
    if( ! $password) {
	warn "Password has not been set in PasswordValue, for vhost $vhostName\n";
	$errors ++;
	next;
    }

    # Are we storing an hashed password or a plain password?
    my $isHashed = 0;
    if($password =~ /^\{CRYPT\}/) {
	$isHashed = 1;
	# Trim the {CRYPT} prefix: htpasswd uses crypt password hashes by default
	$password =~ s/^\{CRYPT\}//;
    } elsif ($password =~ /^\{SHA\}/) {
	$isHashed = 1;
    }
     
    my $action = (-r $passwordFile ? 'update' : 'create');
    if(system($htpasswd, 
	      '-b' . ($action eq 'create' ? 'c' : '') . ($isHashed ? 'p' : 's'), 
	      $passwordFile, 
	      $vhostName, 
	      $password) != 0) {
	warn("Could not $action the htpasswd database file in " . $passwordFile);
	$errors ++;
    }
}

exit ($errors == 0 ? 0 : 1);
