#!/bin/bash
#Some defines
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'


if [ "$EUID" -ne 0 ]; then
        echo -e "${RED}ERROR: Please run as root with sudo${NC}" >&2
        exit 1
fi

echo -e "${GREEN}You are about to *BLAST* away the old CA, please enter Y ro proceed${NC}"
read AGREE


if [ ! "$AGREE" != "${AGREE#[Yy]}" ] ;then
    exit 1
fi

echo "Removeing old files"
rm -r data
rm *.crt
rm *.crl
rm *.key

echo "Building CA"
mkdir -p data
mkdir -p ./data/certs
mkdir -p ./data/newcerts
mkdir -p ./data/crl
if [ ! -f "./data/index.txt" ]; then
        echo "Creating databases index file"
        touch ./data/index.txt
fi

if [ ! -f "./data/crlnumber" ]; then
        echo "Creating crlnumber file"
        echo 1000 >  ./data/crlnumber
fi

echo -e "${GREEN}Please enter starting serial number ${YELLOW}(in HEX)${GREEN} of first certificate signed${NC}"
read SERIAL
if [ ! -f "./data/serial" ]; then
        echo "Creating serial file"
        echo ${SERIAL} >  ./data/serial
fi

echo -e "${GREEN}Enter the name of the Root certificate you are building${NC}"
read NAME
echo -e "${GREEN}Build root certificate for ${NAME}, press enter to continue${NC}"
read DUMMY
openssl req -nodes -x509 -config openssl.cnf -sha384 -newkey rsa:4096 -keyout "${NAME}.key" -out "${NAME}.crt" -days 7305
echo "Display Cert to check"
openssl x509 -noout -text -in ${NAME}.crt
echo -e "${GREEN}Press enter to continue${NC}"
read DUMMY

openssl ca -config openssl.cnf -gencrl -keyfile ${NAME}.key -cert ${NAME}.crt -out root.crl.pem
openssl crl -inform PEM -in root.crl.pem -outform DER -out root.crl
rm root.crl.pem

echo -e "${GREEN}We need to copy the Certificate Revocation List file to a web server, please enter the directory name or ${NC}${YELLOW}none${NC}"
read DIR1
if [ "$DIR1" != "none" ]; then
	cp root.crl ${DIR1}
fi
echo "Done"


