#!/bin/sh
#set -x

# Default prefix
@LOCATION_ENV@=@LOCATION_DIR@

# Logfile location
LOG_DIR=@VAR_DIR@/log/voms

# Trust anchors location
CERTDIR=${CERTDIR:-/etc/grid-security/certificates}

# openssl
SSLPROG="openssl"

# MySQL install prefix
MYSQL_HOME=${MYSQL_HOME:-/usr}

# MySQL install prefix
ORACLE_HOME=${ORACLE_HOME:-/usr/}

# VOMS database
voms_database=""

# VOMS VO
voms_vo=""

# MySQL admin user
db_username_admin="root"
db_password_admin=""

# VOMS query user
voms_username_query=""
voms_password_query=""

ECHO=/bin/echo

# Default path
basepath=$@LOCATION_ENV@
datapath=@ETC_DIR@

# Default Suffix
code=0
compat_mode=""
timeout=30
loglevel=2
logtype=7
logdateformat=""
logformat=""
sqlloc=""
help=""
newformat="yes"
vomscert="/etc/grid-security/voms/hostcert.pem"
vomskey="/etc/grid-security/voms/hostkey.pem"

if test "x@with_mysqlconf@" != "x" ; then
    MYSQLCONF=" --defaults-file=@with_mysqlconf@ "
else
    MYSQLCONF=""
fi


TEMP=`getopt -o h --long vomscert:,vomskey:,mysql-home:,loglevel:,logtype:,logformat:,logdateformat:,oracle-home:,db:,port:,code:,voms-vo:,socktimeout:,db-type:,sqlloc:,db-admin:,db-pwd:,voms-name:,voms-pwd:,newformat,oldformat,compat -n 'voms_install_db' -- "$@"`

if [ $? != 0 ] ; then $ECHO "Terminating..." >&2 ; exit 1 ; fi

eval set -- "$TEMP"

while true ; do
    case "$1" in
  --mysql-home)             MYSQL_HOME=$2              ; shift 2 ;;
  --oracle-home)            ORACLE_HOME=$2             ; shift 2 ;;
  --db)                     voms_database=$2           ; shift 2 ;;
  --port)                   port=$2                    ; shift 2 ;;
  --code)                   code=0                     ; shift 2 ;;
  --voms-vo)                voms_vo=$2                 ; shift 2 ;;
  --db-type)                db_type=$2                 ; shift 2 ;;
  --sqlloc)                 sqlloc=$2                  ; shift 2 ;;
  --db-admin)               db_username_admin=$2       ; shift 2 ;;
  --db-pwd)                 db_password_admin=$2       ; shift 2 ;;
  --voms-name)              voms_username_query=$2     ; shift 2 ;;
  --voms-pwd)               voms_password_query=$2     ; shift 2 ;;
  --compat)                 compat_mode="-compat"      ; shift 1 ;;
  --socktimeout)            timeout=$2                 ; shift 2 ;;
  --loglevel)               loglevel=$2                ; shift 2 ;;
  --logtype)                logtype=$2                 ; shift 2 ;;
  --logformat)              logformat=$2               ; shift 2 ;;
  --logdateformat)          logdateformat=$2           ; shift 2 ;;
  --newformat)              newformat="yes"            ; shift 1 ;;
  --oldformat)              newformat="no"             ; shift 1 ;;
  --vomscert)               vomscert=$2                ; shift 2 ;;
  --vomskey)                vomskey=$2                 ; shift 2 ;;
  -h)                       help="yes"                 ; shift 1 ;;
	--)                       shift                      ; break   ;;
	*)                        $ECHO "$1: Internal Error!" >&2 ; exit 1  ;;
    esac
done

if test "x$help" = "xyes"; then
    $ECHO "USAGE: voms_install_db  [--option value] ... [--option value]"
    $ECHO
    $ECHO "Where --option may be:"
    $ECHO "    --mysql-home path       Where the MySQL installation is based."
    $ECHO "                            Defaults to the value of \$MYSQL_HOME"
    $ECHO "                            if specified, and /usr otherwise. Only"
    $ECHO "                            needed if MySQL support is desired."
    $ECHO "    --oracle-home path      Where the Oracle installation is based."
    $ECHO "                            Only needed if Oracle support is desired."
    $ECHO "                            No defaults."
    $ECHO "    --port port             The port on which the server will listen."
    $ECHO "                            The default value is 15000."
    $ECHO "    --code num              Only present for compatibility with older"
    $ECHO "                            versions of this script.  It is ignored."
    $ECHO "    --voms-vo name          The name of the VO. No defaults."
    $ECHO "    --db-type type          The type of the underlying DB.  Only"
    $ECHO "                           'mysql' and 'oracle' are accepted now."
    $ECHO "                            There are no defaults.  This must always be."
    $ECHO "                            specified."
    $ECHO "    --sqlloc path           The name of the db access library to use."
    $ECHO "                            The library path must be in \$LD_LIRARY_PATH"
    $ECHO "                            or in ld.so.conf, or the option must specify"
    $ECHO "                            the full path. Defaults to libvoms<db>.so."
    $ECHO "    --db-admin name         The name of the DB administrator account."
    $ECHO "                            Defaults to 'root'."
    $ECHO "    --db-pwd password       The password associated to the db-admin account."
    $ECHO "                            No defaults."
    $ECHO "    --voms-name name        The name of the DB account that will be created to"
    $ECHO "                            let VOMS access the DB.  Defaults to voms_<vo name>."
    $ECHO "    --voms-pwd              The password of the previous account.  The default"
    $ECHO "                            is randomly generated."
    $ECHO "    --compat                If specified, allows the server to work with an"
    $ECHO "                            existing DB coming from VOMS 1.4.x or before."
    $ECHO "    --socktimeout sec       Specifies the length of time after which connections"
    $ECHO "                            to the server will be dropped, in seconds.  The"
    $ECHO "                            default is 60 seconds."
    $ECHO "    --loglevel lev          Sets the amount of leveling.  Higher values imply more"
    $ECHO "                            logging. The default is 2. (LOG_ERROR)"
    $ECHO "    --logtype type          Specifies what to log. See the voms(8) man page for details."
    $ECHO "    --logformat format      See the voms(8) man page for details."
    $ECHO "    --logdateformat format  See the voms(8) man page for details."
    $ECHO "    --newformat             Creates AC according to the new format."
    $ECHO "    --oldformat             Creates AC according to the old format."
    $ECHO "    --help                  This output."
    exit 0;
fi
    
if test "x$voms_vo" = "x"; then
  $ECHO "The VO name MUST be specified!"
  exit 1;
fi

if test "x$voms_username_query" = "x"; then
  voms_username_query="voms_"$voms_vo
fi

if test "x$voms_database" = "x"; then
  voms_database="voms_"$voms_vo
fi

if test "x$voms_password_query" = "x"; then
    voms_password_query="`$SSLPROG rand -base64 6`";
fi

if test "x$db_type" != "xmysql"; then
    if test "x$db_type" != "xoracle"; then
        $ECHO "Only 'mysql' or 'oracle' are accepted values for --db-type."
        $ECHO "Instead $db_type was given!"
        exit 1
    fi
fi

if test "x$compat_mode" = "x-compat" ; then
  if test "x$db_type" != "xmysql"; then
      $ECHO "compatibility mode only works with MySQL!";
      exit 1;
  fi
fi

if test "x$sqlloc" = "x"; then
    sqlloc="libvoms$db_type.so"
fi

# choose client
if test "x$db_type" = "xmysql" ; then
    if test -z $db_password_admin ; then
        MYSQLADMIN="$MYSQL_HOME/bin/mysqladmin $MYSQLCONF -u $db_username_admin"
        CLIENT="$MYSQL_HOME/bin/mysql $MYSQLCONF -u $db_username_admin"
    else
        MYSQLADMIN="$MYSQL_HOME/bin/mysqladmin $MYSQLCONF -u $db_username_admin -p$db_password_admin"
        CLIENT="$MYSQL_HOME/bin/mysql $MYSQLCONF -u $db_username_admin -p$db_password_admin"	
    fi
elif test "x$db_type" = "xoracle" ; then
    CLIENT="$ORACLE_HOME/bin/sqlplus -S $db_username_admin/$db_password_admin@$voms_database"
else 
    $ECHO "Please select one beetween --db-type oracle and --db-type mysql."
    exit 1;
fi

# Create Database
if test "x$db_type" = "xmysql" ; then
    $CLIENT -e "DROP DATABASE IF EXISTS $voms_database;
                CREATE DATABASE $voms_database;"
    if test $? -ne 0 ; then
        $ECHO "Could not execute $CLIENT command"
        exit 1;
    fi

    CLIENT="$CLIENT -D$voms_database" 
fi

# Create Tables
$CLIENT < "${basepath}/share/voms/voms-"$db_type$compat_mode".data"

# Create users
if test "x$db_type" = "xmysql" ; then
$CLIENT -e "
  GRANT SELECT         ON $voms_database.*         TO   $voms_username_query              IDENTIFIED BY '$voms_password_query';
  GRANT LOCK TABLES    ON $voms_database.*         TO   $voms_username_query              IDENTIFIED BY '$voms_password_query';

  GRANT SELECT         ON $voms_database.*         TO   $voms_username_query@localhost    IDENTIFIED BY '$voms_password_query';
  GRANT LOCK TABLES    ON $voms_database.*         TO   $voms_username_query@localhost    IDENTIFIED BY '$voms_password_query';

  FLUSH PRIVILEGES;"
fi

# Populate database
$CLIENT <<EOF
-- The transaction counter.  The first real transaction will get CreatedSerial=1.
INSERT INTO ca VALUES (1, '/O=VOMS/O=System/CN=Dummy Certificate Authority', 'A dummy CA for local database maintenance.');
INSERT INTO ca VALUES (2, '/O=VOMS/O=System/CN=Authorization Manager Attributes', 'A virtual CA corresponding to authz manager attributes');
INSERT INTO ca VALUES (3, '/O=VOMS/O=System/CN=VOMS Group', 'A virtual CA corresponding to a VO group');
INSERT INTO ca VALUES (4, '/O=VOMS/O=System/CN=VOMS Role', 'A virtual CA corresponding to a VO role');
INSERT INTO ca VALUES (5, '/O=VOMS/O=System/CN=VOMS Capability', 'A the virtual CA corresponding to a VO capability');
-- The database administrator responsible for these bootstrap records. 
INSERT INTO admins VALUES (1, '/O=VOMS/O=System/CN=Local Database Administrator', '', 1);
-- The VO-Admin role to allow remote administration
INSERT INTO admins VALUES (2, '/$voms_vo/Role=VO-Admin', '', 4);
-- The VO Group.
INSERT INTO groups VALUES (1, '/$voms_vo', 1, 1);
-- The VO Administrators role
INSERT INTO roles VALUES (1, 'VO-Admin');
-- The first timestamp record.
-- INSERT INTO realtime VALUES (0, current_timestamp);
INSERT INTO seqnumber VALUES ('00');
INSERT INTO version (version) VALUES (2);
EOF

# Populate ca table
insert_ca=""
i=5

for cert in $CERTDIR/*.0
do
   i=$(($i + 1))
   subject=`$SSLPROG x509 -noout -subject -in $cert|sed 's/^subject=[ ]*//'`
   cn=`$ECHO $subject|sed -n '/.*\/CN=\([^\/]*\).*/s//\1/p'`
   $CLIENT <<EOF 
INSERT INTO ca VALUES ($i, '$subject', '$cn');
EOF
done

# Creating voms group
#groupadd voms 2>/dev/null

# Creating voms user
#useradd -g voms voms 2>/dev/null

# Setting ownership and permission for voms_password_query file
mkdir -p $datapath/voms/$voms_vo
mkdir -p $LOG_DIR
#$datapath/log
$ECHO $voms_password_query > $datapath/voms/$voms_vo/voms.pass

uid=`/usr/bin/id -u`

[ $uid = "0" ] && chown root.voms $datapath/voms/$voms_vo/voms.pass 
chmod 640 $datapath/voms/$voms_vo/voms.pass

if test -z $voms_vo ; then
    logname=voms
else
    logname=voms.$voms_vo
fi
 
$ECHO -en "--vo=$voms_vo\n--dbname=$voms_database\n--port=$port\n--username=$voms_username_query\n--passfile=$datapath/voms/$voms_vo/voms.pass\n--sqlloc=$sqlloc\n--logfile=$LOG_DIR/$logname\n" > $datapath/voms/$voms_vo/voms.conf
$ECHO -en "--socktimeout=$timeout\n--loglevel=$loglevel\n--logtype=$logtype\n" >>$datapath/voms/$voms_vo/voms.conf

if test "x$compat_mode" = "x-compat"; then
    $ECHO -en "--compat\n" >> $datapath/voms/$voms_vo/voms.conf
fi
if test "x$logformat" != "x"; then
    $ECHO -en "--logformat=\"$logformat\"\n" >> $datapath/voms/$voms_vo/voms.conf
fi
if test "x$logdateformat" != "x"; then
    $ECHO -en "--logdateformat=\"$logdateformat\"\n" >> $datapath/voms/$voms_vo/voms.conf
fi
if test "x$newformat" = "xyes"; then
    $ECHO -en "--newformat\n" >> $datapath/voms/$voms_vo/voms.conf
fi
$ECHO -en "--x509_user_cert=$vomscert\n" >> $datapath/voms/$voms_vo/voms.conf
$ECHO -en "--x509_user_key=$vomskey\n" >> $datapath/voms/$voms_vo/voms.conf
