#!/bin/bash

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


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

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

is_cert_match_private_key() {
    cert=$1
    KEY_PATH="/etc/ssl/private/private.pem"
    diff <(openssl x509 -noout -modulus -in ${cert}) <(openssl rsa -noout -modulus -in "${KEY_PATH}") > /dev/null
}

check_valid_cert() {
    cert_chain=$(cat "${1}")
    is_cert_match_private_key <(echo -e "${cert_chain}")
    if [[ $? -ne 0 ]]; then
        log "user.warning" "First cert should be devices public key"
        return 1
    fi
    cert_count=$(echo -e "${cert_chain}" | 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 1
}

save() {
    certificate=$(cat)
    check_valid_cert <(echo -e "${certificate}")

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

delete_force() {
    ln -sf ${SELF_SIGNED_CERTIFICATE} ${SYMBOLIC_LINK}    
    rm -f ${CA_SIGNED_CERTIFICATE}
    systemctl reload --no-block lighttpd
    log "user.notice" "CA-signed certification file deleted."
}

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

get() {
    if [[ -f "${CA_SIGNED_CERTIFICATE}" ]]; then
        cat ${CA_SIGNED_CERTIFICATE}
    else
        log "user.warning" "CA-signed certification file not found."
        exit 1    
    fi
}

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

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

help() {
echo "Usage: 
    ${script_name} <command>

    Commands:
    -s, --save
        Create the CA-signed certification file and set certification symlink to this file.
    -d, --delete
        Delete the CA-signed certification file if exist and reset certification symlink to the self-signed certification file. Otherwise return error (1).
    -f, --factory
        Delete the CA-signed certification file and reset certification symlink to the self-signed certification file.
    -g, --get
        Return with CA-signed certification file if exist. Otherwise return error (1).
    -i, --info
        Return status of CA-signed certification file: 'Self-signed' or 'Uploaded'
    -c, --check
        Checks uploaded certificate. If there's no uploaded, then return error
    -h, --help
        Show help options.
    "
}

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

case ${1} in
    --save|-s)
        save
        ;;
    --delete|-d)
        delete
        ;;
    --factory|-f)
        delete_force
        ;;
    --get|-g)
        get
        ;;
    --info|-i)
        info
        ;;
    --check|-c)
        check
        ;;
    --help|-h)
        help
        ;;
    *)
        echo "command not found"
        help
        exit 1
        ;;

esac
