#!/bin/bash

set -u

source "$(dirname "${BASH_SOURCE[0]}")/lwr-cert.env"

declare -ir ERR_NO_SUCH_FILE=2
declare -ir ERR_INVALID_ARGUMENT=22

script_name=$(basename -- "$0")
script_name="${script_name%.*}"

log() {
    logger -p "$1" "${script_name} log: $2"
    echo -e "${script_name} debug: $2"
}

check_cert_match_private_key() {
    local -r cert_path="${1}"
    local cert_modulus
    local key_modulus

    cert_modulus=$(openssl x509 -in "${cert_path}" -noout -modulus)
    key_modulus=$(openssl rsa -noout -modulus -in "${PRIVATE_KEY_PATH}")

    [[ "${cert_modulus}" == "${key_modulus}" ]]
}

check_valid_cert_chain() {
    local -r cert_path="${1}"

    check_cert_match_private_key "${cert_path}"
    if [[ $? -ne 0 ]]; then
        log "user.warning" "First cert should be devices public key"
        return "${ERR_INVALID_ARGUMENT}"
    fi
    cert_count=$(cat "${cert_path}" | grep -o 'END CERTIFICATE' | wc -l)
    if [[ ${cert_count} -gt 1 ]]; then
        return 0
    fi
    log "user.warning" "At least 2 certificates should be in chain"
    return "${ERR_INVALID_ARGUMENT}"
}

extract_common_name_from_cert() {
    local -r cert_path="${1}"
    openssl x509 -in "${cert_path}" -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,\/]*\).*/\1/p'
}

check_cert_chain_through_tempfile() {
    local -r certificate="${1}"
    local -r tempfile="/tmp/temp_cert_chain.pem"

    echo -e "${certificate}" > "${tempfile}"
    check_valid_cert_chain "${tempfile}"
    rc=${?}
    rm -f "${tempfile}"
    return ${rc}
}

check_self_signed_cert_through_tempfile() {
    local -r certificate="${1}"
    local -r tempfile="/tmp/temp_self_signed_cert.pem"

    echo -e "${certificate}" > "${tempfile}"
    check_self_signed_cert_content "${tempfile}"
    rc=${?}
    rm -f "${tempfile}"
    return ${rc}
}

patient_restart() {
    nohup bash -c 'logger "Cert changed, restart lighttpd in 3 seconds..." && sleep 3 && systemctl restart lighttpd.service'  >/dev/null 2>&1 &
}

save_uploaded() {
    local -r offline="${1}"
    certificate=$(cat)

    check_cert_chain_through_tempfile "${certificate}"

    if [[ ${?} -eq 0 ]]; then
        echo -e "${certificate}" > ${CA_SIGNED_CERTIFICATE}
        ln -sf ${CA_SIGNED_CERTIFICATE} ${SYMBOLIC_LINK}
        if [[ "${offline}" != "1" ]]; then
            patient_restart
        fi
        log "user.notice" "CA-signed certification file saved."
    else
        log "user.err" "Invalid certificate uploaded"
        exit "${ERR_INVALID_ARGUMENT}"
    fi
}

delete_force() {
    local -r offline="${1}"

    ln -sf ${SELF_SIGNED_CERTIFICATE} ${SYMBOLIC_LINK}
    rm -f ${CA_SIGNED_CERTIFICATE}
    if [[ "${offline}" != "1" ]]; then
        patient_restart
    fi
    log "user.notice" "CA-signed certification file deleted."
}

delete() {
    local -r offline="${1}"

    if [[ -f "${CA_SIGNED_CERTIFICATE}" ]]; then
        delete_force "${offline}"
    else
        log "user.warning" "Can not delete file. CA-signed certification file not found."
        exit "${ERR_NO_SUCH_FILE}"
    fi
}

get_cert_from_path() {
    local -r cert_path="${1}"

    if [[ -f "${cert_path}" ]]; then
        cat "${cert_path}"
    else
        log "user.warning" "Certification file not found."
        exit "${ERR_NO_SUCH_FILE}"
    fi

}

info() {
    if [[ -f "${CA_SIGNED_CERTIFICATE}" ]]; then
        echo -n "Uploaded"
    else
        echo -n "Self-signed"
    fi
}

check_ca_cert() {
    if [[ -f "${CA_SIGNED_CERTIFICATE}" ]]; then
        check_valid_cert_chain ${CA_SIGNED_CERTIFICATE}
    else
        log "user.err" "Check failed: CA-signed certification file not found."
        exit "${ERR_NO_SUCH_FILE}"
    fi
}

check_self_signed_cert_content() {

    local -r cert_path="$1"

    if ! check_cert_match_private_key "${cert_path}"; then
        log "user.err" "Check failed: Self-signed certification does not match with private key."
        return "${ERR_INVALID_ARGUMENT}"
    fi

    if ! does_common_name_match_with_hostname "${cert_path}"; then
        log "user.err" "Check failed: Self-signed certification common name does not match with hostname."
        return "${ERR_INVALID_ARGUMENT}"
    fi
}

check_self_signed_cert() {
    local -r cert_path="${1}"

    if [[ ! -f "${cert_path}" ]]; then
        log "user.err" "Check failed: Self-signed certification file not found."
        return "${ERR_NO_SUCH_FILE}"
    fi
    check_self_signed_cert_content "${cert_path}"
}

does_common_name_match_with_hostname() {
    local -r cert_path="$1"
    local self_signed_common_name
    self_signed_common_name=$(extract_common_name_from_cert "${cert_path}")

    if [[ "${self_signed_common_name}" != "$(hostname)" ]]; then
        return "${ERR_INVALID_ARGUMENT}"
    fi
}

regenerate_self_signed_cert() {
    local -r offline="${1}"

    local hostname
    hostname="$(hostname)"
    local ec="$?"
    if [[ "${ec}" -ne "0" ]]; then
        log "user.err" "Failed to retrieve hostname for self-signed cert generation! (${ec})"
        return "${ec}"
    fi

    mkdir -p "${CERT_PATH}"
    openssl req -key "${PRIVATE_KEY_PATH}" -new -nodes -x509 -days 3650 -subj "/CN=${hostname}" -out "${SELF_SIGNED_CERTIFICATE}"
    ec="$?"
    if [[ "${ec}" -ne "0" ]]; then
        log "user.err" "Failed to regenerate self-signed certificate! (${ec})"
        return "${ec}"
    fi
    log "user.notice" "Self-signed certificate regenerated for hostname: ${hostname}"

    if [[ ! -f "${CA_SIGNED_CERTIFICATE}" ]]; then
        ln -sf ${SELF_SIGNED_CERTIFICATE} ${SYMBOLIC_LINK}
        if [[ "${offline}" != "1" ]]; then
            systemctl restart lighttpd
        fi
    fi
}

regenerate_self_signed_cert_if_needed() {
    local -r offline="${1}"

    if ! check_self_signed_cert "${SELF_SIGNED_CERTIFICATE}"; then
        regenerate_self_signed_cert "${offline}"
        return $?
    fi
}

save_self_signed() {
    local -r offline="${1}"
    local -r certificate="$(cat)"

    mkdir -p "${CERT_PATH}"

    check_self_signed_cert_through_tempfile "${certificate}"

    if [[ ${?} -eq 0 ]]; then
        echo -e "${certificate}" > ${SELF_SIGNED_CERTIFICATE}

        if [[ ! -f "${CA_SIGNED_CERTIFICATE}" ]]; then
            ln -sf ${SELF_SIGNED_CERTIFICATE} ${SYMBOLIC_LINK}
            if [[ "${offline}" != "1" ]]; then
                systemctl restart lighttpd
            fi
        fi
        log "user.notice" "Self-signed certification file saved."
    else
        log "user.err" "Failed to save invalid self-signed certificate."
        exit "${ERR_INVALID_ARGUMENT}"
    fi
}

help_uploaded() {
    echo "
    'uploaded' subcommands:
      save
        Create the CA-signed certification file and set certification symlink to this file.
      delete [--force]
        Delete the CA-signed certification file if exist and reset
        certification symlink to the self-signed certification file.
        Otherwise return error.
        With '--force' passed, certification existence check is skipped,
        no errors returned.
      get
        Return with CA-signed certification file if exist. Otherwise return error.
      check
        Checks uploaded certificate. If there's no uploaded, then return error"
}

help_self_signed() {
    echo "
    'self-signed' subcommands:
      regenerate [--if-needed]
        Regenerate self-signed certificate and restarts webserver,
        if no certificate has been uploaded.
        By passing '--if-needed', certificate is regenerated only if it does
        not exist or its CN does not match with hostname.
      get
        Return self-signed certification file content.
      save
        Stores certificate from <stdin> if it is correct. Checked against private key and hostname.
        Useful for restoring configuration.
      check
        Check self-signed certificate."
}

help() {
    echo "usage: ${script_name} [<options>] <command>
       ${script_name} [<options>] uploaded <subcommands>
       ${script_name} [<options>] self-signed <subcommands>

    Commands:
      info
          Return status of certification file: 'Self-signed' or 'Uploaded'
      get
          Return active certification file content.
      help, -h, --help
        Show help options.

    Options:
      --offline
        if given, do not restart/reload webserver (lighttpd).
    "
    help_uploaded
    help_self_signed
}

#########################
#    start script here
#########################

process_uploaded() {
    local -r offline="${1}"
    shift

    case ${1:-help} in
        save)
            save_uploaded "${offline}"
            ;;
        delete)
            if [[ "${2:-}" == "--force" ]]; then
                delete_force "${offline}"
            else
                delete "${offline}"
            fi
            ;;
        get)
            get_cert_from_path "${CA_SIGNED_CERTIFICATE}"
            ;;
        check)
            check_ca_cert
            ;;
        help)
            help_uploaded
            ;;
        *)
            echo "Subcommand not found: ${1}"
            help_uploaded
            exit 1
            ;;

    esac
}

process_self_signed() {
    local -r offline="${1}"
    shift

    case ${1:-help} in
        regenerate)
            case ${2:-} in
                "--if-needed")
                    regenerate_self_signed_cert_if_needed "${offline}"
                    ;;
                "")
                    regenerate_self_signed_cert "${offline}"
                    ;;
                *)
                echo "Unknown option: ${2}"
                help_self_signed
                exit 1
            esac
            ;;
        save)
            save_self_signed "${offline}"
            ;;
        get)
            get_cert_from_path "${SELF_SIGNED_CERTIFICATE}"
            ;;
        check)
            check_self_signed_cert "${SELF_SIGNED_CERTIFICATE}"
            ;;
        help)
            help_self_signed
            ;;
        *)
            echo "Subcommand not found: ${1}"
            help_self_signed
            exit 1
            ;;
    esac
}

main() {
    local args=()
    local offline=0

    while [[ $# -gt 0 ]]; do
        case ${1} in
            --offline)
                offline=1
                ;;
         *)
             if [[ -n "${1}" ]]; then
                 args+=("${1}")
             fi
        esac
        shift
    done

    case ${args[0]:-help} in
        info)
            info
            ;;
        get)
            get_cert_from_path "${SYMBOLIC_LINK}"
            ;;
        help|--help|-h)
            help
            ;;
        uploaded)
            shift
            process_uploaded "${offline}" ${args[@]:1}
            ;;
        self-signed)
            shift
            process_self_signed "${offline}" ${args[@]:1}
            ;;
        *)
            echo "Command not found: ${1}"
            help
            exit 1
            ;;
    esac
}

main "$@"
