#!/bin/bash

hashPassword()
{
    local password="$1"

    # htpasswd first (local, instant). docker fallback pulls a ~50MB image.
    if command -v htpasswd &>/dev/null; then
        local bcrypt_hash
        bcrypt_hash=$(htpasswd -bnBC 10 "" "$password" | tr -d ':\n')
        if [[ -n "$bcrypt_hash" ]]; then
            bcrypt_hash=$(echo "$bcrypt_hash" | awk -F= '{print $NF}')
            local escaped_hash
            escaped_hash=$(echo "$bcrypt_hash" | sed 's/\$/\$\$/g')
            echo "$escaped_hash"
            return 0
        fi
    fi

    if command -v docker &>/dev/null; then
        local bcrypt_hash
        bcrypt_hash=$(runFileOp docker run --rm ghcr.io/wg-easy/wg-easy wgpw "$password" 2>/dev/null | tr -d '\n')
        if [[ -n "$bcrypt_hash" ]]; then
            bcrypt_hash=$(echo "$bcrypt_hash" | awk -F= '{print $NF}')
            local escaped_hash
            escaped_hash=$(echo "$bcrypt_hash" | sed 's/\$/\$\$/g')
            echo "$escaped_hash"
            return 0
        fi
    fi

    isError "Failed to generate bcrypt hash."
    return 1
}

