#!/bin/bash
# This script is being depricated. Do not use it!

# Update init scripts with service dependenices.
/bin/update-svc-deps

# Set file permission to 640 for sshinfo log file
chmod 0640 /var/log/audit/sshinfo.log

# Reload the firewall in case there were services removed in patch phase
/usr/lib/applmgmt/networking/bin/firewall-reload


# Function to update the password file for observability services
# password files present in /etc/vmware/vmware-vmon/svcCfgfiles/jmx folder
function update_password_file() {
    #Updates the password file in the path /etc/vmware/vmware-vmon/svcCfgfiles/jmx/*.password
    #This will generate random password
    echo "$(date): Inside update_password_file : "
    password=$(cat /dev/urandom | env LC_CTYPE=C tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1)
        for file in /etc/vmware/vmware-vmon/svcCfgfiles/jmx/*.password; do
            echo "observabilityRole $password" > $file
            echo "$(date): Password changed in $file"
        done
    echo "$(date): Password Change is succesfull"
    echo "$(date): Updating database with the new password"

    # Start/Stop of OBS service
    systemctl stop observability
    sqlite3 /storage/db/stellar.db << EOF
    replace into observabilitysettings values ('jmxpassword', "$password");
EOF
    echo "$(date): Password updated in db"
    systemctl start observability
}

if [ -d "/etc/vmware/vmware-vmon/svcCfgfiles/jmx" ]; then
 update_password_file
else
 echo "$(date): Skipping Password update since jmx folder doesnt exist"
fi


# Restore non default certs from the previous JRE installation
certs=$(ls  /tmp/certs)

for cert_file in $certs
do
    alias=$(echo $cert_file | cut -d '.' -f1)
    echo "importing $cert_file with alias $alias"
    check_if_exists=$(keytool -noprompt -storepass changeit -list -trustcacerts -alias "$alias" -keystore /usr/java/jre-vmware/lib/security/cacerts | grep -c 'Certificate fingerprint')

    if [ $check_if_exists -eq 0 ]; then
        keytool -noprompt -storepass changeit -import -trustcacerts -file "/tmp/certs/$cert_file"  -alias $alias -keystore /usr/java/jre-vmware/lib/security/cacerts
    else
        echo "skipping $alias as it already exists in keystore"
    fi

done

rm -rf /tmp/certs

# Ensure CAP is started on leaf service upgrade until they fix their logic
if ! grep -q "VMware-vCenter-Cloud-Gateway" /etc/vmware/.buildInfo && \
 [ -e /usr/lib/systemd/system/cap-workflow-engine.service ] && \
 ! systemctl is-active --quiet cap-workflow-engine.service ; then
    /usr/bin/systemctl start cap-workflow-engine.service
fi

true
