#!/bin/sh
#
# xcrypt_upgrade
#
# This script is used to re-sign the updated/modified config files
# which could happen if the CST version has been changed during upgrade
# of PowerPath.
# 
# Copyright 2008-2012 EMC Corporation.  All rights reserved.
#-----------------------------------------------------------------------

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.1.01.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
{
    local stat
    $*
    stat=$?
    test $stat -ne 0 && SCRIPT_STATUS=$stat
    return $stat
}

function script_exit
{
    exit $SCRIPT_STATUS
}

function script_error
{
    test $SCRIPT_STATUS -ne 0
}

function script_success
{
    return $SCRIPT_STATUS
}

ckm_upgrade ()
{
    echo "`eval_gettext \"Upgrade ckm\"`"

    #-----------------------------
    # Delete 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
        rm -f $cacheFile
    fi

    passopt=${PP_CKM_PASSWD:+"-password"}
    exec_cmd ckmadm upgrade \
             -cache_file $CLIENT/config/km211apps.cache.bak \
             -init_file $CLIENT/config/rkm_init.conf \
             -config_file $CLIENT/config/rkm_svc.conf \
             -keyclass_file $CLIENT/config/rkm_keyclass.conf \
             $passopt ${PP_CKM_PASSWD}
}

#-----------------------------------------------------------------------
# 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()
{
    local 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
}

## Restore the config directory to the state that existed before upgrade.
## Restore lockbox files only if they have changed.

upgrade_rollback()
{
    cmp -s $1/csp.clb $2/csp.clb || cp -p $1/csp.clb $2/csp.clb
    cmp -s $1/csp.clb.bak $2/csp.clb.bak || cp -p $1/csp.clb.bak $2/csp.clb.bak
    cmp -s $1/Config.xml $2/Config.xml || cp -p $1/Config.xml $2/Config.xml
    if [ -f "$1/delete" ]
    then
        for name in `cat $1/delete`
        do
            rm -f $2/$name
        done
    fi

    pwd=`pwd`
    cd $1
    for file in `ls | grep '\.xml$'`
    do
        cp -p $1/$file $2/$file
    done
    cd $pwd
}

#-------------------------------------------------------------------------
# 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 =================================
# set -x
# typeset -f -t `typeset +f`

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

## Dot in the environment variables needed for encryption 

. $EMC/bin/emcp_setup.sh

if [ ! -f "$MARKER" ]
then
    echo "`eval_gettext \"PowerPath Encryption with RSA is not configured. Please execute xcrypt_config instead.\"`"
    exit 
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


## Check for new and changed cst configuration files and "sign" them into
## the cst lockbox.  This is done in two steps.  First, copy new and
## changed files into the config directory.  Second, run "sign-file" on
## the all new and changed file.  If "sign-file" fails, restore the cst
## configuration to its original state.

rm -rf $CST/cfg.bak
mkdir $CST/cfg.bak
cp -p $CST/config/csp.clb $CST/cfg.bak/csp.clb
cp -p $CST/config/csp.clb.bak $CST/cfg.bak/csp.clb.bak
cp -p $CST/config/Config.xml $CST/cfg.bak/Config.xml
changed_file=''
for name in `(cd $CST/xml; echo *)`
do
    if [ "$name" = Config.xml ]
    then
        continue
    fi
    test -f $CST/config/$name && cmp -s $CST/xml/$name $CST/config/$name
    if [ $? -ne 0 ]
    then
        if [ -f $CST/config/$name ]
        then
            mv  -f $CST/config/$name $CST/cfg.bak/$name
        else
            echo $name >> $CST/cfg.bak/delete
        fi
        cp $CST/xml/$name $CST/config/$name
        changed_file=T
    fi
done

if [ "$changed_file" ]
then
    echo -n "Enter the lockbox passphrase: "
    stty -echo
    read LB_PASSPHRASE
    stty echo
    echo ""

    if [ -z "$LB_PASSPHRASE" ]; then
        echo "*** ERROR: The lockbox passphrase is required."
        SCRIPT_STATUS=1
    else
        exec_cmd cstadmin sign-file \
                 -passphrase=${LB_PASSPHRASE} -cstdir=$CST/config \
                 "*.xml"

        if script_success
        then
            exec_cmd cstadmin reset-lockbox \
                     -passphrase=${LB_PASSPHRASE} -cstdir=$CST/config \
                     -threshold=4
        fi
    fi

    if script_error
    then
        echo
        echo "`eval_gettext \"Error while upgrading encryption configuration, rolling back upgrade.\"`"
        upgrade_rollback $CST/cfg.bak $CST/config
        script_exit
    else
        $EMC/bin/xcryptd_adm restart
    fi
fi

## Backup RKM cache file
if [ -f "$CLIENT/config/km211apps.cache" ]
then
    mv -f $CLIENT/config/km211apps.cache $CLIENT/config/km211apps.cache.bak
fi

## Stop xcrypt daemon
exec_cmd $EMC/bin/xcryptd_adm disable

## Upgrade CKM, including upgrade rkm cache
ckm_upgrade

if script_error
then
    echo "`eval_gettext \"Error while upgrading encryption key cache.\"`"

    ## Start xcrypt daemon
    exec_cmd $EMC/bin/xcryptd_adm enable

    exit 1
fi

## Start xcrypt daemon
exec_cmd $EMC/bin/xcryptd_adm enable

rescan_partitions

script_exit
