#!/bin/bash

# This script for automatically apply settings for CryptoPro CSP KC1 or KC2 in Porteus.
# Version 2025-05-03

# Copyright 2025 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.

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

# check if CryptoPro CSP is installed in the system
if [[ -d "/opt/cprocsp" ]]; then
    echo "We continue the execution of the $0 script" &>/dev/null
    else
    echo "You need to install CryptoPro CSP via command: update csp"
    exit
fi

TRIAL=${TRIAL:-5050N-40030-01BT7-2MA83-QF3T0}
BOLD=${BOLD:-"\e[1m"}
CYAN=${CYAN:-"\e[96m"}
GREEN=${GREEN:-"\e[92m"}
RED=${RED:-"\e[31m"}
RESET=${RESET:-"\e[0m"}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    x86_64) ARCH=x86_64 ;;
    *) echo 'Your architecture is not supported' ;;
  esac
fi

if [[ "$ARCH" == i686 || "$ARCH" == i586 ]]; then
    # Porteus PATH setup for CryptoPro CSP
    echo -e "\n[${CYAN}${BOLD}NOTE${RESET}] Run this option only once."
    read -p "$(echo -e 1\) Do you want to set PATH for CryptoPro CSP? [${BOLD}y${RESET}/${BOLD}n${RESET}])" -n 1 -r -s && echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        sed -i "s|ENV_SUPATH     PATH=|ENV_SUPATH     PATH="$(/bin/ls -d /opt/cprocsp/{s,}bin/*|tr '\n' ':')"|g" /etc/login.defs
        sed -i "s|/usr/games|/usr/games:"$(/bin/ls -d /opt/cprocsp/{s,}bin/*|tr '\n' ':'| rev | cut -d: -f2- | rev)"|g" /etc/profile
        PATH="$PATH:/opt/cprocsp/bin/ia32:/opt/cprocsp/sbin/ia32"
        echo '/opt/cprocsp/lib/ia32' >> /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

    # if CryptoPro CSP KC2 installed in the system
    if [[ -f "/opt/cprocsp/sbin/ia32/cryptsrv" ]]; then
    echo -e "[${CYAN}${BOLD}NOTE${RESET}] Run this option only once."
    read -p "$(echo -e 1.1\) Do you want to set and run daemon of CryptoPro CSP KC2? [${BOLD}y${RESET}/${BOLD}n${RESET}])" -n 1 -r -s && echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            echo '/opt/cprocsp/sbin/ia32/cryptsrv' >> /etc/rc.d/rc.local
            /opt/cprocsp/sbin/ia32/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
    fi

    # install license
    read -p "$(echo -e 2\) Do you have license for CryptoPro CSP? [${BOLD}y${RESET}/${BOLD}n${RESET}])" -n 1 -r -s && echo
        if [[ $REPLY =~ ^[Yy]$ ]]; 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

    # install CA certificates
    certmgr=`ls /opt/cprocsp/bin/*/certmgr 2>/dev/null | awk '{ print $1 }'`
    ls -d /var/opt/cprocsp/tmpcerts/root/* | 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/* | xargs -n 1 $certmgr -install -store mca -file 1>/dev/null || printf "Failed to install intermediate certificates! \n"

    # !!! WARNING !!! All installed browsers or mail client must be launched at least once
    # more details - https://www.gosuslugi.ru/crt
    echo -e "[${CYAN}${BOLD}NOTE${RESET}] Run and close all installed browsers or mail client at least once and press '${BOLD}y${RESET}'"
    read -p "$(echo -e 3\) Did you launched all installed browsers or Mozilla Thunderbird at least once? [${BOLD}y${RESET}/${BOLD}n${RESET}])" -n 1 -r -s && echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        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,russian_trusted_sub_ca_pem}.crt && update-ca-certificates --fresh
        # Chromium
        certutil -d sql:/home/guest/.pki/nssdb -A -t "CT,c,c" -n "Russian Trusted Root CA" -i /usr/local/share/ca-certificates/russian_trusted_root_ca_pem.crt
        certutil -d sql:/home/guest/.pki/nssdb -A -t "CT,c,c" -n "Russian Trusted Sub CA" -i /usr/local/share/ca-certificates/russian_trusted_sub_ca_pem.crt
        # Mozilla Firefox
        certutil -d sql:`find /home/guest/.mozilla -name "cert9.db" | sed "s|/cert9.db||"` -A -t "CT,c,c" -n "Russian Trusted Root CA" -i /usr/local/share/ca-certificates/russian_trusted_root_ca_pem.crt
        certutil -d sql:`find /home/guest/.mozilla -name "cert9.db" | sed "s|/cert9.db||"` -A -t "CT,c,c" -n "Russian Trusted Sub CA" -i /usr/local/share/ca-certificates/russian_trusted_sub_ca_pem.crt
        # Mozilla Thunderbird
        certutil -d sql:`find /home/guest/.thunderbird -name "cert9.db" | sed "s|/cert9.db||"` -A -t "CT,c,c" -n "Russian Trusted Root CA" -i /usr/local/share/ca-certificates/russian_trusted_root_ca_pem.crt
        certutil -d sql:`find /home/guest/.thunderbird -name "cert9.db" | sed "s|/cert9.db||"` -A -t "CT,c,c" -n "Russian Trusted Sub CA" -i /usr/local/share/ca-certificates/russian_trusted_sub_ca_pem.crt
        echo -e "\n[${GREEN}${BOLD}OK${RESET}] CA certificates was installed successfully.\n"
        else exit
    fi

elif [[ "$ARCH" == x86_64 ]]; then
    # Porteus PATH setup for CryptoPro CSP
    echo -e "\n[${CYAN}${BOLD}NOTE${RESET}] Run this option only once."
    read -p "$(echo -e 1\) Do you want to set PATH for CryptoPro CSP? [${BOLD}y${RESET}/${BOLD}n${RESET}])" -n 1 -r -s && echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        sed -i "s|ENV_SUPATH     PATH=|ENV_SUPATH     PATH="$(/bin/ls -d /opt/cprocsp/{s,}bin/*|tr '\n' ':')"|g" /etc/login.defs
        sed -i "s|/usr/games|/usr/games:"$(/bin/ls -d /opt/cprocsp/{s,}bin/*|tr '\n' ':'| rev | cut -d: -f2- | rev)"|g" /etc/profile
        PATH="$PATH:/opt/cprocsp/bin/amd64:/opt/cprocsp/sbin/amd64"
        echo '/opt/cprocsp/lib/amd64' >> /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

    # if CryptoPro CSP KC2 installed in the system
    if [[ -f "/opt/cprocsp/sbin/amd64/cryptsrv" ]]; then
    echo -e "[${CYAN}${BOLD}NOTE${RESET}] Run this option only once."
    read -p "$(echo -e 1.1\) Do you want to set and run daemon of CryptoPro CSP KC2? [${BOLD}y${RESET}/${BOLD}n${RESET}])" -n 1 -r -s && echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            echo '/opt/cprocsp/sbin/amd64/cryptsrv' >> /etc/rc.d/rc.local
            /opt/cprocsp/sbin/amd64/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
    fi

    # install license
    read -p "$(echo -e 2\) Do you have license for CryptoPro CSP? [${BOLD}y${RESET}/${BOLD}n${RESET}])" -n 1 -r -s && echo
        if [[ $REPLY =~ ^[Yy]$ ]]; 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

    # install CA certificates
    certmgr=`ls /opt/cprocsp/bin/*/certmgr 2>/dev/null | awk '{ print $1 }'`
    ls -d /var/opt/cprocsp/tmpcerts/root/* | 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/* | xargs -n 1 $certmgr -install -store mca -file 1>/dev/null || printf "Failed to install intermediate certificates! \n"

    # !!! WARNING !!! All installed browsers or mail client must be launched at least once
    # more details - https://www.gosuslugi.ru/crt
    echo -e "[${CYAN}${BOLD}NOTE${RESET}] Run and close all installed browsers or mail client at least once and press '${BOLD}y${RESET}'"
    read -p "$(echo -e 3\) Did you launched all installed browsers or Mozilla Thunderbird at least once? [${BOLD}y${RESET}/${BOLD}n${RESET}])" -n 1 -r -s && echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        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,russian_trusted_sub_ca_pem}.crt && update-ca-certificates --fresh
        # Chromium
        certutil -d sql:/home/guest/.pki/nssdb -A -t "CT,c,c" -n "Russian Trusted Root CA" -i /usr/local/share/ca-certificates/russian_trusted_root_ca_pem.crt
        certutil -d sql:/home/guest/.pki/nssdb -A -t "CT,c,c" -n "Russian Trusted Sub CA" -i /usr/local/share/ca-certificates/russian_trusted_sub_ca_pem.crt
        # Mozilla Firefox
        certutil -d sql:`find /home/guest/.mozilla -name "cert9.db" | sed "s|/cert9.db||"` -A -t "CT,c,c" -n "Russian Trusted Root CA" -i /usr/local/share/ca-certificates/russian_trusted_root_ca_pem.crt
        certutil -d sql:`find /home/guest/.mozilla -name "cert9.db" | sed "s|/cert9.db||"` -A -t "CT,c,c" -n "Russian Trusted Sub CA" -i /usr/local/share/ca-certificates/russian_trusted_sub_ca_pem.crt
        # Mozilla Thunderbird
        certutil -d sql:`find /home/guest/.thunderbird -name "cert9.db" | sed "s|/cert9.db||"` -A -t "CT,c,c" -n "Russian Trusted Root CA" -i /usr/local/share/ca-certificates/russian_trusted_root_ca_pem.crt
        certutil -d sql:`find /home/guest/.thunderbird -name "cert9.db" | sed "s|/cert9.db||"` -A -t "CT,c,c" -n "Russian Trusted Sub CA" -i /usr/local/share/ca-certificates/russian_trusted_sub_ca_pem.crt
        echo -e "\n[${GREEN}${BOLD}OK${RESET}] CA certificates was installed successfully.\n"
        else exit
    fi
fi