#!/bin/sh
#
# Iniialize and configure PowerPath Data at Rest Encryption.
#
# Copyright 2008-2014 EMC Corporation.  All rights reserved.
#-----------------------------------------------------------------------

# Main

PATH=/usr/bin:/usr/sbin:/bin:/sbin; export PATH
LD_LIBRARY_PATH=/etc/emc/rsa/cst/lib; export LD_LIBRARY_PATH

PPBASE="/etc/opt/emcpower/EMCpower.LINUX-5.7.5.00.00"

# the following are the internationalization specific lines

if [ ! -x /usr/bin/gettext ]; then
gettext()
{
 echo "$*"
}
eval_gettext()
{
 eval "echo \"$*\""
}

else
. gettext.sh
TEXTDOMAIN=PowerPath
export TEXTDOMAIN
TEXTDOMAINDIR=$PPBASE/i18n/catalog

export TEXTDOMAINDIR
export RPM_INSTALL_PREFIX
fi
# end of internationalization






#-----------------------------------------------------------------------
# Functions to exec a command and remember the return status
#-----------------------------------------------------------------------
SCRIPT_STATUS=0

function exec_cmd
{
    typeset stat
    $*
    stat=$?
    test $stat -ne 0 && SCRIPT_STATUS=$stat
    return $stat
}

function script_success
{
    return $SCRIPT_STATUS
}

function script_exit
{
    exit $SCRIPT_STATUS
}

#-----------------------------------------------------------------------
# valid_license_key - Check the license for the product name passed in
# $1.  Return an okay status if the user has a valid license for that
# product.
#-----------------------------------------------------------------------
valid_license_key()
{
    typeset product

    product=`echo $1 | tr -d ' '`

    ## Use awk to generate lines of product name and product validity.
    ## Then use grep to select the product we are interested in.

    /sbin/emcpreg -list |\
    tr -d ' ' |\
    awk -F: '/Product/ {prod = $2; val[prod] = "valid"; next}
              /Expired/ {val[prod] = "expired"; next}
              /Key/ {print val[prod], prod}
              END {print val[prod], prod}' |\
    grep valid  |\
    grep $product >/dev/null
}

start_daemon()
{
    exec_cmd $EMC/bin/xcryptd_adm enable
}

rollback()
{
    rm -f $EMC/rsa/cst/config/*.xml
    rm -f $EMC/rsa/cst/config/*.xsd
    rm -f $EMC/rsa/cst/config/csp.clb
    rm -f $EMC/rsa/cst/config/csp.clb.bak
    rm -f $EMC/rsa/rkm_client/config/km211apps.cache
}

cst_configure()
{
    echo "`eval_gettext \"Configuring cst\"`"
    if [ "$PP_CST_PASSWD" ]
    then
        passopt="-passphrase=${PP_CST_PASSWD}"
    fi
    cp -p $CST/xml/*.xml $CST/config
    cp -p $CST/xml/*.xsd $CST/config
    exec_cmd cstadmin initialize $CST/config $passopt -unattended \
                                 -overwrite -threshold=4
}

ckm_configure()
{
    echo "`eval_gettext \"Configuring ckm\"`"
    passopt=${PP_CKM_PASSWD:+"-password"}
    exec_cmd ckmadm setup -file $CLIENT/config/rkm_init.conf \
                                            $passopt ${PP_CKM_PASSWD}
    script_success && \
        exec_cmd ckmadm setConfig -file $CLIENT/config/rkm_svc.conf
    script_success && \
         exec_cmd ckmadm setKeyClass \
               -file $CLIENT/config/rkm_keyclass.conf 
}

#-------------------------------------------------------------------------
# After the daemon is started, the encryption states of the devices will
# be automatically updated.  However the partition tables on the encrypted
# devices will not be updated.  Hence wait for sometime for the key states
# to be updated and run 'blockdev --rereadpt' on each of those encrypted
# devices for which key state has been updated properly.
#-------------------------------------------------------------------------
rescan_partitions()
{
    for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
    do
        /sbin/powervt xcrypt -info -dev all 2>&1 |
            grep -q "no key is available"
        if [ $? -eq 1 ]; then
            break
        fi
        sleep 10
    done

    keys_not_available_count=0
    for dev in `/sbin/powervt xcrypt -info -dev all 2>&1 |
                grep "is encrypted" |
                sed -e 's/\(emcpower.*\) is encrypted.*/\1/'`
    do
        /sbin/powervt xcrypt -info -dev $dev -refresh 2>&1 |
            grep -q "no key is available"
        if [ $? -eq 1 ]; then
            /sbin/blockdev --rereadpt /dev/${dev} > /dev/null 2>&1
        else
            keys_not_available_count=`expr ${keys_not_available_count} + 1`
            keys_not_available_list[keys_not_available_count]=/dev/${dev}
        fi
    done

    if [ $keys_not_available_count -gt 0 ]; then
        echo
        echo "`eval_gettext \"Partition tables on the following devices may not have been\"`"
        echo "`eval_gettext \"updated as the encryption keys are not available yet.  Please\"`"
        echo "`eval_gettext \"run 'blockdev --rereadpt' on these devices once the keys are\"`"
        echo "`eval_gettext \"available.\"`"

        count=0;
        while [ $count -lt $keys_not_available_count ]; do
            count=`expr $count + 1`;
            echo "   " ${keys_not_available_list[${count}]}
        done
        echo
    fi
}

#================================= Main =================================

EMC=/etc/emc
CST=$EMC/rsa/cst
CLIENT=$EMC/rsa/rkm_client
MARKER=$EMC/.xcrypt_cfg_done

rpm -qi EMCpower.LINUX > /dev/null 2>&1
if [ $? -ne 0 ]
then
    echo "`eval_gettext \"Cannot find PowerPath package base.\"`"
    exit 1
fi

### Check root authorization
ruid=`id -ru`
euid=`id -u`
if [ $ruid -ne 0 -o $euid -ne 0 ]; then
    echo
    echo "`eval_gettext \"Insufficient user privilege.\"`"
    echo
    script_exit 
fi

valid_license_key "PowerPath Encryption"
if [ $? -ne 0 ]
then
    cmd=`basename $0`
    echo "`eval_gettext \"A valid license key for PowerPath Encryption with RSA was not found.\"`"
    echo "`eval_gettext \"Please register a valid license and re-run \\$cmd.\"`"
    exit 1
fi

## If .xcrypt_cfg_done exists, this script has been run before and
## should not be run again
if [ -f "$MARKER" ]
then
    echo "`eval_gettext \"PowerPath Encryption with RSA is already configured.  Exiting.\"`"
    exit 0
fi

## Check if PowerPath is active
lsmod | grep -w '^emcp' > /dev/null 2>&1
if [ $? -ne 0 ]
then
    echo "`eval_gettext \"PowerPath modules are not loaded.\"`"
    echo "`eval_gettext \"Ensure that the modules are loaded and try again.\"`"
    exit 1
fi

## Dot in the environment variables needed for encryption 
. $EMC/bin/emcp_setup.sh

cst_configure

ckm_configure

if script_success
then
    #-----------------------------
    # Backup target cache file specified in the rkm_init.conf file
    #-----------------------------
    cacheFile=`sed -n -e '/^persistentCacheFile/s/.*=//p' \
               $CLIENT/config/rkm_init.conf`

    if [ -f "$cacheFile" ]
    then
        mv -f $cacheFile $cacheFile.bak
    fi

    touch $MARKER
    start_daemon
    rescan_partitions
else
    rollback
fi

script_exit
