#!/usr/bin/env bash
#chkconfig: 35 20 80
#description: Agent server

basePath=$(cd `dirname $0`/; pwd)
baseDirPath="${basePath}"
serviceName=$(basename ${basePath})
encryptionKeyPath="${basePath}/config/encryptionKey"

uniqueId="d94d3a4"
packageName=$(basename `find ${basePath}/*.jar`)

encryptionKey="encryptionKey"

function setKey()
{
   if [[ -s ${encryptionKeyPath} ]]
   then
       echo "the encryption key already exists. You don't need to set a new key."
   else
       echo "Notes: encryption key will not be stored, please keep it properly."
       echo "please enter the encryption key: "
       read -s encryptionKeyValue
       if [[ $? -eq 0 ]]
       then
           echo "setKey=true ${encryptionKey}=${encryptionKeyValue}" | java -jar ${basePath}/${packageName}
           echo "the encryption key setting succeeds."
           return 0
       fi
       echo "failed to set the encryption key."
   fi
}

function encrypt()
{
    if [[ -s ${encryptionKeyPath} ]]
    then
        echo "please enter what you want to encrypt content: "
        read -s plaintext
        if [[ $? -eq 0 ]]
        then
            echo "isSensitive=true plaintext=${plaintext}" | java -jar ${basePath}/${packageName}
            return 0
        fi
        echo "encryption failed."
    else
        echo "please set the encryption key first."
    fi
}

function updateKey()
{
    if [[ -s ${encryptionKeyPath} ]]
    then
        echo "Notes: encryption key will not be stored, please keep it properly."
        echo "please enter the encryption key: "
        read -s encryptionKeyValue
        if [[ $? -eq 0 ]]
        then
           echo "setKey=true ${encryptionKey}=${encryptionKeyValue}" | java -jar ${basePath}/${packageName}
           echo "update the encryption key successfully."
           return 0;
        fi
    else
        echo "please set a encryption key first."
    fi
}

if [[ ${#} -ge 1 ]]
then
    case ${1} in
        "setKey")
            setKey
        ;;
        "encrypt")
            encrypt
        ;;
        "updateKey")
            updateKey
        ;;
        *)
            echo "${1} No operation"
        ;;
    esac
else
    echo "
    command: setKey/encrypt/updateKey

    command example: ./encrypt setKey
    "
fi
