#!/usr/bin/

#Delete file if exists

rm -rf /opt/HyperPKI
rm -rf /usr/share/applications/HyperPKIManger.desktop
rm -rf ~/.pki/nssdb


usbreset 2ccf:080a
usbreset 096e:080a

# Check if libnss3-tools is installed
if ! dpkg -l libnss3-tools &> /dev/null; then
    echo "libnss3-tools is not installed. Installing..."
    sudo apt-get update
    sudo apt-get install -y libnss3-tools
else
    echo "libnss3-tools is already installed."
fi

if ! dpkg -l libcanberra-gtk-module &> /dev/null; then
    echo "libnss3-tools is not installed. Installing..."
    sudo apt-get update
    sudo apt-get install -y libcanberra-gtk-module
else
    echo "libcanberra-gtk-module is already installed."
fi
# Create an NSS database (nssdb) and set the owner to the current user
mkdir -p /home/"$USER"/.pki/nssdb
#certutil -N -d ~/.pki/nssdb

sudo cp -avr "./libcastle_v2.so.1.0.0" /usr/local/lib/
sudo chown -R "$LOGNAME":"$LOGNAME"  /usr/local/lib/libcastle_v2.so.1.0.0
sudo chown -R "$LOGNAME":"$LOGNAME"  /home/"$LOGNAME"/.pki/nssdb

# Add PKCS11 from /usr/lib to the nssdb
modutil -add "HYP2003" -libfile /usr/local/lib/libcastle_v2.so.1.0.0 -dbdir /home/"$LOGNAME"/.pki/nssdb

#Import CCA Inida 2022 As trusted Root Certifying Authority
certutil -A -n "CCA India 2022" -i ./CCAIndia2022.cer -t "CT,CT,CT" -d /home/"$LOGNAME"/.pki/nssdb

sudo certutil -L -d ~/.pki/nssdb/ -h all

echo "NSS database created and PKCS11 module added.
To set the ~/.pki/nssdb in LibreOffice, you can do the following:
1. Open Tools > Options
2. Expand LibreOffice and select Security from the left-hand menu tree
3. Click the Certificate button under Certificate Path on the right
4. Click Add in the Certificate Path dialog box
5. Press Ctrl + L to manually enter the location in the Select Path dialog box
6. Type ~/.pki/nssdb/ and click OK
7. Click OK to close the Certificate Path dialog box
8. Click OK to close the Options dialog box
9. Restart LibreOffice"

# Check if the XDG_CURRENT_DESKTOP environment variable is set
if [ -z "$XDG_CURRENT_DESKTOP" ]; then

echo "No GUI Detected"

else

sudo mkdir -p /opt/HyperPKI/
#sudo chown -R "$LOGNAME":"$LOGNAME" /opt/HyperPKI/
sudo cp HyperPKIManger /opt/HyperPKI/
sudo cp HyperPKIManger.ico /opt/HyperPKI/

sudo chmod +x /opt/HyperPKI/HyperPKIManger
sudo chmod 755 -R /opt/HyperPKI
#sudo cp -avr lang /opt/HyperPKI/


# The text you want to add
TEXT="[Desktop Entry]
Name=HPY2003 Token Manager
Comment=HyperPKI_HPY2003 Token Manager
Exec=/opt/HyperPKI/HyperPKIManger
Icon=/opt/HyperPKI/HyperPKIManger.ico
Terminal=false
Type=Application
Categories=HYP2003 USB Token Manager"

file_location=/usr/share/applications/HyperPKIManger.desktop

# The file you want to write to
FILE="/usr/share/applications/HyperPKIManger.desktop"

# Append text to the file with root privileges
echo "$TEXT" | sudo tee -a "$FILE" > /dev/null

fi
sudo update-desktop-database
sudo mkdir -p /etc/pki/
sudo cp -r /home/"$LOGNAME"/.pki/nssdb /etc/pki/