#!/bin/bash

# This script for automatically apply settings for CryptoPro CSP KC1 or KC2 in Porteus.
# Version 2026-07-15

# Copyright 2026 Blaze, Dankov, Russia
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# ----------------------------------------------------------------------
# Colors and constants
# ----------------------------------------------------------------------
BOLD="\e[1m"
CYAN="\e[96m"
GREEN="\e[92m"
RED="\e[31m"
RESET="\e[0m"

TRIAL="5050N-40030-01BT7-2MA83-QF3T0"

# ----------------------------------------------------------------------
# Root check
# ----------------------------------------------------------------------
if [ "$(whoami)" != "root" ]; then
    echo -e "\nOnly root can run this.\n"
    exit 1
fi

# ----------------------------------------------------------------------
# Check if CryptoPro CSP is installed
# ----------------------------------------------------------------------
if [ ! -d "/opt/cprocsp" ]; then
    echo "You need to install CryptoPro CSP via command: update csp"
    exit 1
fi

# ----------------------------------------------------------------------
# Architecture detection
# ----------------------------------------------------------------------
case "$(uname -m)" in
    i?86)   ARCH="i586" ;;
    x86_64) ARCH="x86_64" ;;
    *)      echo "Your architecture is not supported"; exit 1 ;;
esac

# Set architecture-dependent paths
case "$ARCH" in
    i586) CSP_ARCH="ia32" ;;
    x86_64) CSP_ARCH="amd64" ;;
esac

CSP_BIN="/opt/cprocsp/bin/$CSP_ARCH"
CSP_SBIN="/opt/cprocsp/sbin/$CSP_ARCH"
CSP_LIB="/opt/cprocsp/lib/$CSP_ARCH"
CRYPTSRV="/opt/cprocsp/sbin/$CSP_ARCH/cryptsrv"

# Locate certmgr binary (used for CryptoPro and GIS NR certificates)
CERTMGR=$(ls /opt/cprocsp/bin/*/certmgr 2>/dev/null | awk '{ print $1 }')

# ----------------------------------------------------------------------
# Helper: ask user a yes/no question
# ----------------------------------------------------------------------
ask_yes_no() {
    local prompt="$1"
    local reply
    echo -ne "${prompt} [${BOLD}y${RESET}/${BOLD}n${RESET}] "
    read -n 1 -r reply
    echo
    [ "$reply" = "y" ] || [ "$reply" = "Y" ]
}

# ----------------------------------------------------------------------
# 1. Setup PATH for CryptoPro CSP
# ----------------------------------------------------------------------
setup_path() {
    if grep -q 'cprocsp' /etc/login.defs 2>/dev/null; then
        echo -e "\n[${GREEN}${BOLD}OK${RESET}] PATH for CryptoPro CSP is already set.\n"
        return
    fi

    if ask_yes_no "1) Do you want to set PATH for CryptoPro CSP?"; then
        local newpath=""
        for dir in /opt/cprocsp/bin/* /opt/cprocsp/sbin/*; do
            if [ -d "$dir" ]; then
                newpath="${newpath}${dir}:"
            fi
        done
        newpath=${newpath%:}

        sed -i "s|ENV_SUPATH     PATH=|ENV_SUPATH     PATH=${newpath}|g" /etc/login.defs
        sed -i "s|/usr/games|/usr/games:${newpath}|g" /etc/profile
        export PATH="$PATH:$CSP_BIN:$CSP_SBIN"
        echo "$CSP_LIB" >> /etc/ld.so.conf
        echo '/sbin/ldconfig' >> /etc/rc.d/rc.local
        /sbin/ldconfig
        echo -e "\n[${GREEN}${BOLD}OK${RESET}] PATH is installed successfully.\n"
    else
        echo "We continue the execution of the $0 script" &>/dev/null
    fi
}

# ----------------------------------------------------------------------
# 2. Setup and run cryptsrv daemon (if KC2 is present)
# ----------------------------------------------------------------------
setup_daemon() {
    if [ ! -f "$CRYPTSRV" ]; then
        return
    fi

    if grep -q "$CRYPTSRV" /etc/rc.d/rc.local 2>/dev/null; then
        echo -e "[${GREEN}${BOLD}OK${RESET}] cryptsrv daemon is already set to autostart."
        return
    fi

    if ask_yes_no "1.1) Do you want to set and run daemon of CryptoPro CSP KC2?"; then
        echo "$CRYPTSRV" >> /etc/rc.d/rc.local
        $CRYPTSRV &
        echo -e "\n[${GREEN}${BOLD}OK${RESET}] cryptsrv daemon is running successfully.\n"
    else
        echo "We continue the execution of the $0 script" &>/dev/null
    fi
}

# ----------------------------------------------------------------------
# 3. Install or check license
# ----------------------------------------------------------------------
install_license() {
    if [ -f "/etc/opt/cprocsp/license.ini" ]; then
        echo -e "\n[${GREEN}${BOLD}OK${RESET}] CryptoPro CSP license is already installed."
        echo -e "If you need to change the license, you can do it via CLI: ${BOLD}cpconfig -license -set <serial_number>${RESET}"
        echo -e "or via GUI in CryptoPro Tools."
        return
    fi

    if ask_yes_no "2) Do you have license for CryptoPro CSP?"; then
        echo -e "\nPlease type your serial number in the format\nas example: ${BOLD}${TRIAL}${RESET}\nand press 'Enter' button\n"
        read SERIAL
        cpconfig -license -set "$SERIAL"
        if [ $? -eq 0 ]; then
            echo -e "\n[${GREEN}${BOLD}OK${RESET}] Your ${BOLD}$SERIAL${RESET} installed successfully.\n"
        else
            echo -e "[${RED}${BOLD}ERROR${RESET}] Sorry but your serial is invalid and trial serial on 90 days was applied.\nYou can setup your correct serial in GUI via cptools.\n"
            cpconfig -license -set "$TRIAL"
        fi
    else
        echo -e "\n[${GREEN}${BOLD}OK${RESET}] Trial serial on 90 days was applied.\nYou can setup your correct serial in GUI via cptools.\n"
        cpconfig -license -set "$TRIAL"
    fi
}

# ----------------------------------------------------------------------
# 4. Install CryptoPro CSP root and intermediate certificates
# ----------------------------------------------------------------------
install_crypto_certs() {
    echo -e "\n[${CYAN}${BOLD}NOTE${RESET}] Installing CryptoPro CSP root and intermediate CA certificates..."
    ls -d /var/opt/cprocsp/tmpcerts/root/* 2>/dev/null | xargs -n 1 $CERTMGR -install -store mroot -file 1>/dev/null || printf "Failed to install root certificates!\n"
    ls -d /var/opt/cprocsp/tmpcerts/ca/* 2>/dev/null | xargs -n 1 $CERTMGR -install -store mca -file 1>/dev/null || printf "Failed to install intermediate certificates!\n"
    echo -e "[${GREEN}${BOLD}OK${RESET}] CryptoPro CSP root and intermediate CA certificates installed successfully.\n"
}

# ----------------------------------------------------------------------
# 5. Install Russian Trusted Root CA and Sub CA (Ministry of Digital Development, Federal Treasury, etc.)
# ----------------------------------------------------------------------
install_russian_system_certs() {
    echo -e "[${CYAN}${BOLD}NOTE${RESET}] Installing Russian Trusted CA and additional certificates into browsers..."
    mkdir -p /usr/local/share/ca-certificates
    wget -q --show-progress -P /usr/local/share/ca-certificates \
        https://gu-st.ru/content/lending/russian_trusted_root_ca_pem.crt \
        https://gu-st.ru/content/lending/russian_trusted_sub_ca_pem.crt
    update-ca-certificates --fresh
}

# ----------------------------------------------------------------------
# 6. Import certificates into browsers and additional stores
# ----------------------------------------------------------------------
install_browser_certs() {
    local rca="/usr/local/share/ca-certificates/russian_trusted_root_ca_pem.crt"
    local sca="/usr/local/share/ca-certificates/russian_trusted_sub_ca_pem.crt"
    local nssdb_chromium="/home/guest/.local/share/pki/nssdb"

    # --- Chromium and Chromium-Gost ---
    if [ -f "/usr/bin/chromium-gost-stable" ] || [ -f "/opt/chromium-gost/chromium-gost" ] || [ -f "/usr/bin/chromium" ]; then
        if [ ! -f "$nssdb_chromium/cert9.db" ]; then
            mkdir -p "$nssdb_chromium"
            certutil -N -d sql:"$nssdb_chromium" --empty-password
            chown -R guest:users "/home/guest/.local/share/pki"
        fi
        certutil -d sql:"$nssdb_chromium" -A -t "CT,c,c" -n "Russian Trusted Root CA" -i "$rca"
        certutil -d sql:"$nssdb_chromium" -A -t "CT,c,c" -n "Russian Trusted Sub CA" -i "$sca"

        # RecordSupport Root CA (only for Chromium)
        if [ -d "/opt/recordsupport" ]; then
            certutil -d sql:"$nssdb_chromium" -A -t "C,," -n "RecordSupport Root CA" -i /opt/recordsupport/cert/rootCA.pem
        fi
    fi

    # --- Mozilla Firefox ---
    if [ -f "/usr/bin/firefox" ]; then
        if [ ! -d "/home/guest/.config/mozilla/firefox" ]; then
            sudo -u guest firefox -CreateProfile "default" 2>/dev/null
        fi
        local ff_nssdb
        ff_nssdb=$(find /home/guest/.config/mozilla/firefox -name "cert9.db" -print -quit 2>/dev/null | sed "s|/cert9.db||")
        if [ -n "$ff_nssdb" ]; then
            certutil -d sql:"$ff_nssdb" -A -t "CT,c,c" -n "Russian Trusted Root CA" -i "$rca"
            certutil -d sql:"$ff_nssdb" -A -t "CT,c,c" -n "Russian Trusted Sub CA" -i "$sca"
        else
            echo "Warning: Firefox NSS DB not found, skipping certificate installation for Firefox." >&2
        fi
    fi

    # --- Mozilla Thunderbird ---
    if [ -f "/usr/bin/thunderbird" ]; then
        if [ ! -d "/home/guest/.thunderbird" ]; then
            sudo -u guest thunderbird -CreateProfile "default" 2>/dev/null
        fi
        local tb_nssdb
        tb_nssdb=$(find /home/guest/.thunderbird -name "cert9.db" -print -quit 2>/dev/null | sed "s|/cert9.db||")
        if [ -n "$tb_nssdb" ]; then
            certutil -d sql:"$tb_nssdb" -A -t "CT,c,c" -n "Russian Trusted Root CA" -i "$rca"
            certutil -d sql:"$tb_nssdb" -A -t "CT,c,c" -n "Russian Trusted Sub CA" -i "$sca"
        else
            echo "Warning: Thunderbird NSS DB not found, skipping certificate installation for Thunderbird." >&2
        fi
    fi

    # --- ГИС НР ---
    if [ -d "/opt/nr-plugin" ]; then
        $CERTMGR -install -store mRoot -file "/opt/nr-plugin/share/root.cer" -certificate
        $CERTMGR -install -store mRoot -file "/opt/nr-plugin/share/mincomsvyaz.cer" -certificate
    fi

    echo -e "\n[${GREEN}${BOLD}OK${RESET}] CA certificates was installed successfully.\n"
}

# ----------------------------------------------------------------------
# Main execution flow
# ----------------------------------------------------------------------
setup_path
setup_daemon
install_license
install_crypto_certs
install_russian_system_certs
install_browser_certs
