#!/usr/bin/env bash
set -e

# Get script name
script=$(basename "$0")
version="1.0.0"

# Display Help
help() {
    local script="$1"
    echo
    echo "$script"
    echo
    echo 'Description: Retrieve secret from Ansible Vault.'
    echo "Syntax: $script [-i inventory] [-l host] [-k key] [-V|help]"
    echo "Example: $script -i inventories/odoo -l zeus_erp -k vault_odoo_master_password"
    echo 'options:'
    echo '  -i    Inventory name.'
    echo '  -l    Ansible hostname.'
    echo '  -k    Vault key variable to grep.'
    echo "  -V    Show $script version."
    echo "  help  Show $script manual."
    echo
}

# Show help and exit
if [[ "$1" == "help" ]]; then
    help "$script"
    exit
fi

# Process params
while getopts ":i:l:k:V" opt; do
    case $opt in
        i) inventory_path="$OPTARG";;
        l) host="$OPTARG";;
        k) vault_key="$OPTARG";;
        V) echo "$script version $version"
           exit 0
        ;;
        \?) echo "Invalid option -$OPTARG" >&2
            help "$script"
            exit 1
        ;;
    esac
done

config_file="$HOME/.ansible-vault-get.conf"

if [[ ! -f "$config_file" ]]; then
    echo "Error: Configuration file '$config_file' not found."
    echo "Please init config file with this command:"
    echo "echo \"ANSIBLE_PATH=/path/to/ansible\" > $config_file"
    exit 1
fi

[[ -z "$inventory_path" ]] && { echo "Parameter -i|inventory path is empty" ; exit 1; }
[[ -z "$host" ]] && { echo "Parameter -l|host is empty" ; exit 1; }
[[ -z "$vault_key" ]] && { echo "Parameter -k|key is empty" ; exit 1; }


# Load the inventory path from the configuration file
ansible_path=$(grep "ANSIBLE_PATH" "$config_file" | cut -d '=' -f2)

if [[ -z "$ansible_path" ]]; then
    echo "Error: Ansible path $ansible_path not found."
    echo "Update config file with this command:"
    echo "vi $config_file"
    exit 1
fi

cd "$ansible_path"
source ./task source >/dev/null

vault_file="$inventory_path/host_vars/$host/vault.yml"

if [[ ! -f "$vault_file" ]]; then
    echo "Error: Vault file '$vault_file' not found."
    exit 1
fi

echo $(ansible-vault view "$vault_file" | grep "${vault_key}:" | cut -d ':' -f2)
