#!/usr/bin/perl

# Given a list of directories (for example, /var/satellite)
# check if they exist and if they do not exist, create them
# with apache as owner. Also run restorecon on them, and
# if they are nfs_t mounted, set spacewalk_nfs_mountpoint boolean.

use strict;
use warnings FATAL => 'all';

use Spacewalk::Setup ();

my %dirs;
@dirs{@ARGV} = ();

# Add both potential Apache group IDs (SUSE/RHEL)
my $apache_uid = (getpwnam('wwwrun') // "") . (getpwnam('apache') // "");
if ($apache_uid eq "" ) {
        die "Failed to retrieve uid of user apache, the user does not seem to exist.\n";
}
my $seen_nfs = 0;
for my $dir (sort { length $a <=> length $b } keys %dirs) {
        if (not -e $dir) {
                my @parts = grep { $_ ne '' } split /\//, $dir;
                my $path = '';
                for my $p (@parts) {
                        $path .= "/$p";
                        if (not -e $path) {
                                mkdir $path, 0755 or die "Error creating directory [$path]: $!\n";
                        }
                }
        }
        chown $apache_uid, -1, $dir or die "Error chowning dir [$dir] to [wwwrun]: $!\n";
        my @paths = $dir;
        if (-l $paths[0]) {
                # if the path is a symlink, we will try to restorecon
                # the target as well
                push @paths, "$paths[0]/.";
        }
        if (Spacewalk::Setup::have_selinux()) {
                for my $path (@paths) {
                        my $type = `ls -d -Z -- $path`;
                        if (defined $type
                                and $type =~ /^.+?:.+?:(.+?)(:|\s)/
                                and $1 eq 'nfs_t') {
                                $seen_nfs = 1;
                        } else {
                                if (Spacewalk::Setup::have_selinux()) {
                                        system('/sbin/restorecon', '-r', $path);
                                }
                        }
                }
        }
}
if ($seen_nfs and Spacewalk::Setup::have_selinux()) {
        system('/usr/sbin/setsebool', '-P', 'spacewalk_nfs_mountpoint', 1);
        system('/usr/sbin/setsebool', '-P', 'cobbler_use_nfs', 1);
}

exit 0;

=pod

=head1 NAME

spacewalk-make-mount-points - prepare directories for Spacewalk

=head1 SYNOPSIS

spacewalk-make-mount-points [DIR1 [DIR2 ...]]

=head1 DESCRIPTION

Given a list of directories (for example, /var/satellite) this
script will check if directories exist and if they do not exist,
create them with apache as owner. Also run restorecon on them,
and if they are nfs_t mounted, set spacewalk_nfs_mountpoint
boolean.

This script is not intended to be run directly by human.
spacewalk-setup use this script internally.

=head1 SEE ALSO

spacewalk-setup(8)

=head1 COPYRIGHT AND LICENSE

Copyright (c) 2011--2015 Red Hat, Inc.
Released under GNU General Public License, version 2 (GPLv2).

=cut
