#!/bin/sh
# Copyright (c) 2020 Mastercard

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# wrapper script for NSS (softokn3) tokens
# see with_pkcs11_common for usage and alternate invocations
#
# NSS-specific notes:
#   - slot 1 is used (slot 0 is the NSS internal slot)
#   - PKCS11NSSDIR points to the NSS *database* directory (not the library),
#     defaulting to the conventional per-user NSS DB sql:$HOME/.pki/nssdb.
#     Set it in .pkcs11rc (or the environment) to use a different location.
#   - to create an NSS token: modutil -dbdir sql:. -create
#                              modutil -dbdir sql:. -changepw "NSS Certificate DB"
#   - NSS_LIB_PARAMS is forwarded to the command if set (typically useful with
#     recent NSS versions only)

PKCS11SLOT=1
# The password is a bit different than usual, this one should satisfy password complexity requirements
PKCS11PASSWORD=${PKCS11PASSWORD:-ch@nge1t}
# Default NSS database directory: the conventional per-user NSS DB
# ($HOME/.pki/nssdb), where Chrome/Chromium, p11-kit, etc. keep the user
# database.  We deliberately do NOT fall back to the current directory ("sql:."),
# which would be surprising and risky; set PKCS11NSSDIR in .pkcs11rc (or the
# environment) to use a different location.
PKCS11NSSDIR=${PKCS11NSSDIR:-sql:$HOME/.pki/nssdb}

# PKCS11NSSDIR is the primary NSS database directory for this wrapper and for
# pkcs11-tools NSS initialization. The p11_post_rc hook runs *after* .pkcs11rc
# has been sourced and validates PKCS11NSSDIR first.
#
# Option 3 (advanced fallback): if PKCS11NSSDIR is explicitly unset/empty, the
# hook falls back to configDir found in NSS_LIB_PARAMS when present.
p11_post_rc()
{
    _nssdbspec=
    _nssdbsource=

    # Primary source: PKCS11NSSDIR (matches what pkcs11-tools uses with -m).
    if [ -n "${PKCS11NSSDIR:-}" ]; then
        _nssdbspec=$PKCS11NSSDIR
        _nssdbsource="PKCS11NSSDIR"
    else
        # Advanced fallback: configDir from NSS_LIB_PARAMS when PKCS11NSSDIR is
        # explicitly empty/unset.
        case "${NSS_LIB_PARAMS:-}" in
        configDir=*|*[!_a-zA-Z0-9]configDir=*)
            _nssdbspec=${NSS_LIB_PARAMS#*configDir=}
            # Value may be single-quoted, double-quoted, or bare.
            case "$_nssdbspec" in
            \'*) _nssdbspec=${_nssdbspec#\'}; _nssdbspec=${_nssdbspec%%\'*} ;;
            \"*) _nssdbspec=${_nssdbspec#\"}; _nssdbspec=${_nssdbspec%%\"*} ;;
            *) _nssdbspec=${_nssdbspec%% *} ;;
            esac
            _nssdbsource="NSS_LIB_PARAMS"
            ;;
        esac
    fi

    [ -n "$_nssdbspec" ] || return 0

    # Strip a leading database-type prefix ("sql:", "dbm:", ...) to get the path.
    _nssdir=${_nssdbspec#*:}
    if [ -n "$_nssdir" ] && [ ! -d "$_nssdir" ]; then
        echo "***Error: NSS database directory '$_nssdir' does not exist ($_nssdbsource='$_nssdbspec')." >&2
        echo "          Create it first, e.g.:  mkdir -p '$_nssdir' && certutil -N -d '$_nssdbspec'" >&2
        echo "          or set PKCS11NSSDIR (or NSS_LIB_PARAMS configDir when PKCS11NSSDIR is unset) to an existing directory." >&2
        exit 1
    fi
    unset _nssdir _nssdbspec _nssdbsource
}

_p11_vendor=nss

# vendor-specific settings
case $(uname -s) in
    Darwin) PKCS11_LIBNAME=libsoftokn3.dylib ;;
    *)      PKCS11_LIBNAME=libsoftokn3.so    ;;
esac
PKCS11_LIBPATHS="/usr/lib/$(uname -m)-linux-gnu/nss /usr/local/opt/nss/lib"
LIB_ENVVARS="NSS_LIB_PARAMS"

# load common logic
. "$(dirname "$0")/with_pkcs11_common" "$@"
