#!/usr/bin/perl -w

#
# Copyright (C) 2016 Nethesis S.r.l.
# 
# 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 User::pwent;
use User::grent;

my $event = shift;
my $vhostName = shift;
my $errors = 0;
my $ownerUser = 'ftp';
my $owningGroup = 'apache';

die "[ERROR] vhost argument missing" unless defined ($vhostName);

my $vhostPath = '/var/lib/nethserver/vhost/' . $vhostName;
if ( ! -d $vhostPath ) {
    mkdir $vhostPath;
}

my $ownerEnt = getpwnam($ownerUser);

if (!$ownerEnt) {
    $errors ++;
    warn "[ERROR] Couldn't set \"$ownerUser\" as shared folder owner\n";
}

my $groupEnt = getgrnam($owningGroup);
if(!$groupEnt) {
    $errors ++;
    warn "[ERROR] Couldn't set owning group \"$owningGroup\" on shared folder\n";
}

if ($errors == 0) {
    chown($ownerEnt->uid, $groupEnt->gid, $vhostPath);
    chmod(02755, $vhostPath);
    exit 0;
}

exit 1;
