#!/bin/bash
#
#Josh Randall
#joshua.randall@rsa.com
#15OCT2019

#Update 19DEC2019
#   -implemented more accurate java version & path detection for JDK variable
#   -implemented 30 second timeout on s_client command
#   -implemented additional check on address of hosting server
#   -implemented more accurate keystore import error check
#   -script will show additional URLs for certs with Subject Alternate Names


#set output colors
RED=`tput setaf 1`
GRB=`tput setaf 2; tput bold`
YLW=`tput setaf 3`
BLB=`tput setaf 4; tput bold`
BLD=`tput bold`
RST=`tput sgr0`
#
#set java variable
javaVer=$(java -version 2>&1 | awk '/Runtime/{print $5}' | sed 's/[_-]/./g; s/)//')
javaPath=$(ls /usr/lib/jvm | grep -P "^java.+?$javaVer")
JDK="/usr/lib/jvm/$javaPath/jre"
#set cert file path
CERT="/root/cert.cer"

#grab server cert, write to file, and update /etc/hosts
while true; do
    echo ""
    read -p "Enter the IP or FQDN of the server hosting the CSV file: ${BLB}" SERVER
    if [ -z "$SERVER" ]; then
            echo "${RED}${BLD}Cannot be blank, please try again${RST}"
    elif [ -n "$SERVER" ]; then
        certTMP=$(echo | timeout 30 openssl s_client -connect $SERVER:443 2>/dev/null)
        if [ -n "$certTMP" ]; then
            subjAltNames=$(echo "$certTMP" | openssl x509 -text -noout | grep DNS | sed 's/. DNS:/ /g' |  tr -s ' ')
            echo "$certTMP" | openssl x509 -outform der -out $CERT
            echo -e "${RST}\nCertificate for ${BLB}$SERVER${RST} written to $CERT"
            certCN=$(echo "$certTMP" | grep -Po "0 s.*" | sed 's/.*CN=//')
            echo -e "${RST}\nCertificate CN is ${BLB}$certCN${RST}"
            if [[ "$SERVER" != "localhost" && "$SERVER" != "127.0.0.1" && "$SERVER" != `hostname` && "$SERVER" != `ip addr | grep -o $SERVER` ]]; then
                checkIP=$(ipcalc -c $SERVER 2>&1)
                if [[ $checkIP == "ipcalc: bad IPv4 address: $SERVER" ]]; then
                    ipAddr=$(nslookup $SERVER | grep -Po "Address: .*" | sed 's/Address: //')
                else
                    ipAddr=$SERVER
                fi
            elif [[ "$SERVER" == "localhost" || "$SERVER" == "127.0.0.1" || "$SERVER" == `hostname` || "$SERVER" == `ip addr | grep -o $SERVER` ]]; then
                ipAddr='127.0.0.1'
            else
                :
            fi
            echo -e "${RST}\nBacking up /etc/hosts to /etc/hosts.bak"
            echo -e "${RST}and inserting entry for CN: ${BLB}$certCN${RST}"
            cp /etc/hosts /etc/hosts.bak
            if [[ "$ipAddr" == "127.0.0.1" ]]; then
                sed -i "/127.0.0.1/s/$/ $certCN $subjAltNames/" /etc/hosts
            else
                echo -e "$ipAddr\t$certCN $subjAltNames" >> /etc/hosts
            fi
            break
        elif [ -z "$certTMP" ]; then
            echo -e "${RED}${BLD}\nCould not connect to "$SERVER", please try again${RST}"
        else
            echo -e "${RED}${BLD}\nYou have somehow managed to break this script in a completely unexpected way. Exiting...${RST}"
            exit 1
        fi
    else
        echo -e "${RED}${BLD}\nYou have somehow managed to break this script in a completely unexpected way. Exiting...${RST}"
        exit 1
    fi
done

#import cert.cer file into cacerts java keystore
while true; do
    echo -e "${RST}\nEnter an alias for the certificate"
    read -p "This alias will be how you can find or delete this certificate in the future: ${BLB}" ALIAS
    if [ -z "$ALIAS" ]; then
            echo -e "${RED}${BLD}\nCannot be blank, please try again\n${RST}"
    elif [ -n "$ALIAS" ]; then
        echo -e "${RST}\nAlias: ${GRB}$ALIAS \n${RST}"
        read -p "${YLW}Are you sure this is the alias you want? ${BLB}(y/N)${RST} " continue
        case $continue in
            [yY]* ) echo "";
                "$JDK"/bin/keytool -import -trustcacerts -alias "$ALIAS" -file "$CERT" -noprompt -keystore "$JDK"/lib/security/cacerts -storepass changeit;
                importTest=$("$JDK"/bin/keytool -list -alias "$ALIAS" -keystore $JDK/lib/security/cacerts -storepass changeit);
                if [[ $importTest == *"keytool error"* ]]; then
                    echo -e "${RED}${BLD}$importTest\nImport was not successful, please try again. Exiting...${RST}"
                    exit 1
                else
                    echo -e "The certificate's entry in the truststore is:\n${GRB}"
                    echo "$importTest"
                fi
                break;;

            [nN]* ) continue;;

            * ) echo -e "${RED}${BLD}Invalid choice${RST}";;
        esac
    else
        echo -e "${RED}${BLD}\nYou have somehow managed to break this script in a completely unexpected way. Exiting...${RST}"
        exit 1
    fi
done

#restart the UI for changes to take effect
while true; do
    echo -e "${RST}\nThe UI must be restarted for changes to take effect"
    echo "${YLW}${BLD}This will interrupt any active user sessions"
    echo "And take roughly 5 minutes to complete${RST}"
    read -p "Restart now? ${BLB}(y/N)${RST} " RESTART
        case $RESTART in
            [yY]* ) echo -e "\nRestarting...";
                systemctl restart nginx;
                systemctl restart jetty;
                echo -e "\nServices have been restarted, check for UI availability in ~2 minutes"
                break;;

            [nN]* ) echo -e "\nYou can restart the UI services at your convenience with commands\n";
                echo -e "\t${BLB}systemctl restart nginx; systemctl restart jetty${RST}";
                break;;

            * ) echo "${RED}${BLD}Choose Y or N, please${RST}";;
        esac
done

#print the URL(s) that can be used to access the CSV file
echo -e "\nAfter UI restart, test your custom feed with this URL:"
if [[ "$ipAddr" == "127.0.0.1" ]]; then
    echo -e "\n\t${GRB}https://$certCN/nwrpmrepo/${YLW}<file.csv>${RST}\n"
else
    echo -e "\n\t${GRB}https://$certCN/${YLW}<path/to/file.csv>${RST}\n"
fi
if [[ -n $subjAltNames ]]; then
    echo -e "\n.... or any of these additional URLs using the certificate's Subject Alternate Name values:"
    for altName in $subjAltNames; do
        if [[ "$ipAddr" == "127.0.0.1" ]]; then
            echo -e "\n\t${GRB}https://$altName/nwrpmrepo/${YLW}<file.csv>${RST}\n"
        else
            echo -e "\n\t${GRB}https://$altName/${YLW}<path/to/file.csv>${RST}\n"
        fi
    done
else
    exit 1
fi
