#!/bin/bash

cert_ca="/C=PT/ST=Coimbra/L=Coimbra/O=UC/CN=CoimbraVPN"
cert_vpn="/C=PT/ST=Coimbra/L=Coimbra/O=UC/CN=gateway"
cert_user="/C=PT/ST=Coimbra/L=Coimbra/O=UC/CN=warrior"
cert_apache="/C=PT/ST=Coimbra/L=Coimbra/O=UC/CN=apache.coimbra"

[[ -e "serial" ]]       || echo 1000 > serial
[[ -e "index.txt" ]]    || touch index.txt
[[ -e "ca.key" ]]       || openssl genrsa -out "ca.key" 2048
[[ -e "ca.crt" ]]       || openssl req -x509 -nodes -days 365 -key "ca.key" -out "ca.crt" -subj "$cert_ca"
[[ -e "vpn.key" ]]      || openssl genrsa -out "vpn.key" 2048
[[ -e "vpn.csr" ]]      || openssl req -new -key "vpn.key" -out "vpn.csr" -subj "$cert_vpn"
[[ -e "vpn.crt" ]] 	    || openssl ca -batch -in "vpn.csr" -cert "ca.crt" -keyfile "ca.key" -out "vpn.crt" -config cheese.cfg
[[ -e "dh2048.pem" ]]   || openssl dhparam -out "dh2048.pem" 2048
[[ -e "ta.key" ]]       || openvpn --genkey secret "ta.key"
[[ -e "user.key" ]]     || openssl genrsa -out user.key
[[ -e "user.csr" ]]     || openssl req -new -key user.key -out user.csr -subj "$cert_user"
[[ -e "user.crt" ]] 	|| openssl ca -batch -in "user.csr" -cert "ca.crt" -keyfile "ca.key" -out "user.crt" -config cheese.cfg
[[ -e "apache.key" ]]   || openssl genrsa -out apache.key
[[ -e "apache.csr" ]]   || openssl req -new -key apache.key -out apache.csr -subj "$cert_apache" -addext "subjectAltName = IP:10.60.0.1,DNS:apache"
[[ -e "apache.crt" ]] 	|| openssl ca -batch -in "apache.csr" -cert "ca.crt" -keyfile "ca.key" -out "apache.crt" -config cheese.cfg
