#!/usr/bin/perl -w 
#
# Copyright (c) 2006 Zmanda Inc.  All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# 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
#
# Contact information: Zmanda Inc, 505 N Mathlida Ave, Suite 120
# Sunnyvale, CA 94085, USA, or: http://www.zmanda.com
#
#
use warnings;
use strict;
use Getopt::Long;

my $ZRM_BASEDIR="/etc/mysql-zrm";

#Set ENV variables
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
$ENV{'PATH'} = "/usr/local/bin:/opt/csw/bin:/usr/bin:/usr/sbin:/sbin:/bin";       

my @DIRLIST = qw(
			/var/lib/mysql-zrm
			/var/log/mysql-zrm
			/etc/mysql-zrm
			/usr/share/mysql-zrm
			/usr/local/lib/mysql-zrm
		);

my $FILELIST = "/usr/local/bin/mysql-zrm";

my %opt;
my $USAGE_STRING =
                "mysql-zrm-set-permissions --user <user> --group <group> [--destination <dest>]\n";

#This subroutine logs the error message and exits
sub logAndDie() 
{
	print STDOUT "$_[0]\n";
	&my_exit(1);
}

#This subroutine logs the given message in the log file created at the start
sub logMessage()
{
	print STDOUT "$_[0]\n";
}

sub usage()
{
	print $USAGE_STRING;
	&my_exit(1);
}

sub my_exit()
{
	exit($_[0]);
}

sub doSetPermissions()
{
	foreach( @DIRLIST ){
		if( ! -x $_ ){
			&logMessage( "Could not find $_" );
			next;
		}
#		&logMessage( "Setting permissions for $_" );
		my $r = system( "chown", "-R", "$opt{user}:$opt{group}", $_ );
		if( $r != 0 ){
			&logMessage( "Unable to set permissions for $_. $!i" );
		}
	}
	my @x = <$FILELIST*>;
	foreach( @x ){
		if( ! -x $_ ){
			&logMessage( "Could not find $_" );
			next;
		}
#		&logMessage( "Setting permissions for $_" );
		my $r = system( "chown", "$opt{user}:$opt{group}", "$_" );
		if( $r != 0 ){
			&logMessage( "Unable to set permissions for $_. $!i" );
		}
	}
}

sub main()
{
        my @o = qw/
		user=s
		group=s
		destination=s
                /;

        my $ret = GetOptions( \%opt,
                        @o
                        );
	if( !defined $opt{user} || ! defined $opt{group} ){
		&usage();
	}

	if( defined $opt{destination} ){
		push @DIRLIST, $opt{destination};
	}
	&doSetPermissions();
}#end of init

&main();
&my_exit(0);
