#!/usr/bin/perl
#
#Copyright (c) Members of the EGEE Collaboration. 2004-2009.
#See http://www.eu-egee.org/partners/ for details on the copyright
#holders.
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
#


# This script query the CREAM DB to check if submission are disabled
# or not
# Returns 0 if submissions are enabled
# Returns 1 if submissions are disabled because of the limiter
# Returns 2 if submissions are disabled because of the disable operation
# Returns a value > 2 if some error occurred


use strict;
use FileHandle;
use POSIX qw(strftime);



# Read in the configuration file (first argument)

my $confile;

my %config = (
        DBHost => '',
        CreamDBName => '',
        MinPrivDBUser => '',
        MinPrivDBPassword => '',
              );

if ($ARGV[0]){
    $confile = $ARGV[0];
    my $fh = new FileHandle $confile
        or die "Error: Can't open configuration file: $ARGV[0]\n";
    foreach (<$fh>){
        if ((! m/^\#/) & (m/=/)){
# For lines containing an = and not starting with #
            m/^(.*?)=\s*(.*)\s*$/;
# Split on the first =, no leading or trailing whitespace in the value
            my $key=$1;
            my $value=$2;
            $key=~s/\s+//g;
            $config{$key}=$value;
        }
    }
}else{
 print STDERR "Usage: glite-ce-check-submission-state <config-file> \n";
 exit 99;
}


# Read from configuration file values needed to access the DB

my $dbhost= $config{DBHost};
my $creamdbname = $config{CreamDBName};
my $userdb= $config{MinPrivDBUser};
my $passworddb = $config{MinPrivDBPassword};


# Query the DB to check if submissions are enabled are disabled

my $querycmd= "mysql -B --skip-column-names -h " . $dbhost . " -u " . $userdb . " --password=\"" . $passworddb . "\" -e \"use $creamdbname; select submissionEnabled from db_info;\"";


# Returns value read from the DB if the query was run without problems
# Returns 2 otherwise

my $x=`$querycmd`;
if ($? == 0)
  {
   exit $x
  }
else {
      exit 3;
     }
