#!/bin/bash

# This script tests the basic functionality of mysql-secret-store-login-path.

set -e

TEST_PASSWORD="testpassword"

ROOT_PASSWORD_KEY_JSON=$(cat <<EOF
{
"ServerURL": "root@localhost:3306",
"SecretType": "password"
}
EOF
)

ROOT_PASSWORD_JSON=$(echo "$ROOT_PASSWORD_KEY_JSON" | jq ". + {\"Secret\": \"$TEST_PASSWORD\"}")

# Save password for the root user using mysql-secret-store-login-path store.
save_test_password() {
    mysql-secret-store-login-path store <<< $ROOT_PASSWORD_JSON
}

# Extract password for the root user using mysql-secret-store-login-path get.
get_test_password() {
    mysql-secret-store-login-path get <<< $ROOT_PASSWORD_KEY_JSON | jq -r '.Secret'
}

# Erase password for the root user using mysql-secret-store-login-path erase.
erase_test_password() {
    mysql-secret-store-login-path erase <<< $ROOT_PASSWORD_KEY_JSON
}

# Get the number of stored secrets with mysql-secret-store-login-path list.
get_number_of_secrets() {
    mysql-secret-store-login-path list | jq length
}


# Start by checking that no secrets are stored by default.
NUM_SECRETS=$(get_number_of_secrets)

if [ "$NUM_SECRETS" != 0 ]; then
    echo "Error: No secrets should exist by default, but $NUM_SECRETS were found."
    exit 1
fi

# Add the test password as a secret then make sure it exists and is correct.
save_test_password

NUM_SECRETS=$(get_number_of_secrets)

if [ "$NUM_SECRETS" != 1 ]; then
    echo "Error: Only 1 secret should exist after adding the test password, but $NUM_SECRETS were found."
    exit 1
fi

EXTRACTED_PASSWORD=$(get_test_password)

if [ "$TEST_PASSWORD" != "$EXTRACTED_PASSWORD" ]; then
    echo "Error: Extracted password differs from original, expected:"
    echo $TEST_PASSWORD
    echo "found:"
    echo $EXTRACTED_PASSWORD
    exit 1
fi

# Remove the test secret then confirm there are no secrets left.
erase_test_password

NUM_SECRETS=$(get_number_of_secrets)

if [ "$NUM_SECRETS" != 0 ]; then
    echo "Error: No secrets should exist after removal of test secret, but $NUM_SECRETS were found."
    exit 1
fi
