#!/usr/bin/env bash

list-agekeys() {
    local age_key_file="$HOME/.config/sops/age/keys.txt"

    if [[ ! -f "$age_key_file" ]]; then
        echo "Age key file not found: $age_key_file"
        return 1
    fi

    local created=""
    local public_key=""
    local name=""

    while IFS= read -r line || [[ -n "$line" ]]; do
        if [[ "$line" == '# created:'* ]]; then
            created="${line#\# created: }"
        elif [[ "$line" == '# public key:'* ]]; then
            public_key="${line#\# public key: }"
        elif [[ "$line" == '# name:'* ]]; then
            name="${line#\# name: }"
        elif [[ "$line" == AGE-SECRET-KEY-* ]]; then
            if [[ -n "$public_key" ]]; then
                printf '%s' "$public_key"
                if [[ -n "$name" ]]; then
                    printf ' (%s)' "$name"
                fi
                if [[ -n "$created" ]]; then
                    printf ' %s' "$created"
                fi
                printf '\n'
            fi
            created=""
            public_key=""
            name=""
        fi
    done < "$age_key_file"
}
lak() {
    list-agekeys "$@"
}
