#!/usr/bin/bash

# SHLINT:yes
# Copyright (c) 2021-2022 by NetApp, Inc.
# All Rights Reserved.

#
# This script recovers the server.cfg file using material from
# the ekmip_partition_cfg SMF table
#
# usage: netapp_recover_server_cfg.sh
#

readonly KMIP_SERVER_DIR="/cfcard/kmip/server"
readonly KMIP_SERVER_CFG="${KMIP_SERVER_DIR}/server.cfg"
readonly KMIP_SERVER_CFG_ORIG="${KMIP_SERVER_DIR}/server.cfg.orig"

readonly EPK_AGENT_LOG_FILE="${KMIP_SERVER_DIR}/epk_agent.log"

readonly AWK="/usr/bin/awk"
readonly CAT="/bin/cat"
readonly CP="/bin/cp"
readonly EPK_AGENT="/usr/sbin/epk_agent"
readonly GREP="/usr/bin/grep"
readonly NGSH="/sbin/ngsh -c"
readonly RM="/bin/rm"
readonly SUDO="/usr/bin/sudo"
readonly TAIL="/usr/bin/tail"
readonly TR="/usr/bin/tr"

# files produced by script
readonly EPK_AGENT_INPUT="/tmp/epk_agent_in.txt"
readonly OUTPUT="/tmp/ekmip_partition_cfg_out.txt"
readonly OUTPUT_DOS="/tmp/ekmip_partition_cfg_out.txt.dos"
readonly OUTPUT_DATE="/tmp/date_out.txt"

# node-uuid
readonly NODE_UUID=$(kenv bootarg.bootmenu.node_uuid)

${RM} -f {EPK_AGENT_INPUT}
${RM} -f {OUTPUT}
${RM} -f {OUTPUT_DOS}
${RM} -f {OUTPUT_DATE}

# capture date SMF output
${SUDO} ${NGSH} "set diag; date" > ${OUTPUT_DATE}

# capture ekmip_partition SMF output
${SUDO} ${NGSH} "set diag; debug smdb table ekmip_partition show -node-uuid ${NODE_UUID}" | ${GREP} -v entries > ${OUTPUT_DOS}
if [[ -s ${OUTPUT_DOS} ]]; then
    ${TR} -d '\015' < ${OUTPUT_DOS} > ${OUTPUT}
fi

# create key=value pairs from ekmip_partition SMF output
if [[ -s ${OUTPUT} ]]; then
    ${RM} -f ${EPK_AGENT_INPUT}
    ${CAT} ${OUTPUT} | ${TAIL} -n +4 | ${GREP} -v "entries were displayed" | ${GREP} -v ^$ | \
        ${AWK} '{ \
            printf("mop_epk.%s.server\n", $2); \
            printf("%s.%s\n", $2, $4); \
            printf("mop_epk.%s.kek.label\n", $2); \
            printf("%s\n", $7); \
            printf("mop_epk.%s.kek.epk_key_id\n", $2); \
            printf("%s\n", $5); \
            printf("mop_epk.%s.kek.value.protected\n", $2); \
            printf("%s\n", $6); \
        }' >> ${EPK_AGENT_INPUT}

    echo "$0: restoring server.cfg found on `date` (`date +%s`)" >> ${EPK_AGENT_LOG_FILE}
    if [[ -f ${KMIP_SERVER_CFG_ORIG} ]]; then
        ${CP} ${KMIP_SERVER_CFG_ORIG} ${KMIP_SERVER_CFG}
        echo "$0: server.cfg.orig restored to server.cfg on `date` (`date +%s`)" >> ${EPK_AGENT_LOG_FILE}
    else
        echo "$0: fatal error: server.cfg.orig not found on `date` (`date +%s`)" >> ${EPK_AGENT_LOG_FILE}
    fi

    # fix-up server.cfg
    if [[ -s ${EPK_AGENT_INPUT} ]]; then
        echo "$0: updating server.cfg at `date` (`date +%s`)" >> ${EPK_AGENT_LOG_FILE}
        ${CAT} ${EPK_AGENT_INPUT} | ${EPK_AGENT}
        echo "$0: finished updating server.cfg at `date` (`date +%s`)" >> ${EPK_AGENT_LOG_FILE}
    fi
fi

exit 0
