#!/usr/bin/env bash

remove-agekey-block() {
    local target_public_key="$1"
    local key_file="$2"
    local -a block_lines=()
    local block_public_key=""

    while IFS= read -r line || [[ -n "$line" ]]; do
        if [[ "$line" == AGE-SECRET-KEY-* ]]; then
            block_lines+=("$line")
            if [[ "$block_public_key" != "$target_public_key" ]]; then
                printf '%s\n' "${block_lines[@]}"
            fi
            block_lines=()
            block_public_key=""
        elif [[ "$line" == '# public key:'* ]]; then
            block_public_key="${line#\# public key: }"
            block_lines+=("$line")
        elif [[ "$line" == '#'"*" ]]; then
            block_lines+=("$line")
        fi
    done < "$key_file"
}

extract-agekey-block() {
    local target_public_key="$1"
    local key_file="$2"
    local -a block_lines=()
    local block_public_key=""

    while IFS= read -r line || [[ -n "$line" ]]; do
        if [[ "$line" == AGE-SECRET-KEY-* ]]; then
            block_lines+=("$line")
            if [[ "$block_public_key" == "$target_public_key" ]]; then
                printf '%s\n' "${block_lines[@]}"
                return 0
            fi
            block_lines=()
            block_public_key=""
        elif [[ "$line" == '# public key:'* ]]; then
            block_public_key="${line#\# public key: }"
            block_lines+=("$line")
        elif [[ "$line" == '#'"*" ]]; then
            block_lines+=("$line")
        fi
    done < "$key_file"

    return 1
}

load-agekey-from-keepass() {
    local project_name
    project_name=$(basename -s .git "$(git remote get-url origin 2>/dev/null)" 2>/dev/null)
    project_name=${project_name:-${PWD##*/}}

    local key_name
    key_name=$(echo "${1:-$project_name}" | tr '[:upper:]' '[:lower:]')
    local age_dir="$HOME/.config/sops/age"
    local age_key_file="$age_dir/keys.txt"
    local keepass_entry="age/$key_name"
    local attachment_name="keys.txt"

    mkdir -p "$age_dir"

    local attachment
    attachment=$(mktemp)
    echo "Restore age key '$key_name' from keepassxc: $keepass_entry"
    keepassxc-cli attachment-export \
        --key-file "$KEEPASS_DATABASE_KEY_FILE" \
        "$KEEPASS_DATABASE_FILE" \
        "$keepass_entry" \
        "$attachment_name" \
        "$attachment"

    local public_key
    public_key=$(grep '^# public key:' "$attachment" | head -1 | cut -d: -f2 | tr -d ' ')
    if [[ -z "$public_key" ]]; then
        echo "Could not determine public key from attachment"
        rm -f "$attachment"
        return 1
    fi

    if [[ -f "$age_key_file" ]]; then
        local existing_block
        existing_block=$(mktemp)
        if extract-agekey-block "$public_key" "$age_key_file" > "$existing_block"; then
            if diff -q "$existing_block" "$attachment" >/dev/null 2>&1; then
                echo "Age key '$key_name' is already present and identical in $age_key_file."
                rm -f "$attachment" "$existing_block"
                return 0
            else
                echo "Error: Age key '$key_name' already exists in $age_key_file but differs from KeePassXC entry."
                echo "Refusing to overwrite local key. Remove the existing key manually if you want to replace it."
                rm -f "$attachment" "$existing_block"
                return 1
            fi
        fi
        rm -f "$existing_block"
    fi

    local tmp_key_file
    tmp_key_file="${age_key_file}.tmp"
    if [[ -f "$age_key_file" ]]; then
        cp "$age_key_file" "$tmp_key_file"
    else
        : > "$tmp_key_file"
    fi

    cat "$attachment" >> "$tmp_key_file"
    mv "$tmp_key_file" "$age_key_file"
    chmod 600 "$age_key_file"
    rm -f "$attachment"

    echo "Merged age key '$key_name' into $age_key_file."
}
lakfk() {
    load-agekey-from-keepass "$@"
}
