#!/usr/bin/env bash
# ==========
# Script creates konfiguration for a given key name
# ==========
script_dir="$(dirname $(realpath $0))"
log_file="$(mktemp)"
_date="$(date +%Y-%m-%d-%H%M)"
key_names_reserverd="ta ca server"
#---------------------------------------
#-----------------------------
# Some functions
#-----------------------------
#---------------------------------------
clean_up() {
   # Perform program exit housekeeping
   rm $log_file
   exit $1
}
trim() {
    local var="$*"
    var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters
    var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
    echo -n "$var"
}
is_number() {
   return $(test ! -z "${1##*[!0-9]*}" > /dev/null 2>&1);
   # - also possible
   # -
   #[[ ! -z "${1##*[!0-9]*}" ]] && return 0 || return 1
   #return $([[ ! -z "${1##*[!0-9]*}" ]])
}
is_int() {
   return $(test "$@" -eq "$@" > /dev/null 2>&1);
}
echononl(){
   echo X\\c > /tmp/shprompt$$
   if [ `wc -c /tmp/shprompt$$ | awk '{print $1}'` -eq 1 ]; then
      echo -e -n "$*\\c" 1>&2
   else
       echo -e -n "$*" 1>&2
   fi
   rm /tmp/shprompt$$
}
error(){
   echo ""
   echo -e "\t[ \033[31m\033[1mError\033[m ]: $*"
   echo ""
}
fatal(){
   echo ""
   echo -e "\t[ \033[31m\033[1mFatal\033[m ]: $*"
   echo ""
   echo -e "\t\033[37m\033[1mInstalllation will be interrupted\033[m\033[m"
   echo ""
   clean_up 1
}
warn (){
   echo ""
   echo -e "\t[ \033[33m\033[1mWarning\033[m ]: $*"
   echo ""
}
info (){
   echo ""
   echo -e "\t[ \033[32m\033[1mInfo\033[m ]: $*"
   echo ""
}
echo_done() {
   echo -e "\033[80G[ \033[32mdone\033[m ]"
}
echo_ok() {
   echo -e "\033[80G[ \033[32mok\033[m ]"
}
echo_warning() {
   echo -e "\033[80G[ \033[33m\033[1mwarn\033[m ]"
}
echo_failed(){
   echo -e "\033[80G[ \033[1;31mfailed\033[m ]"
}
echo_skipped() {
   echo -e "\033[80G[ \033[37mskipped\033[m ]"
}
trap clean_up SIGHUP SIGINT SIGTERM
clear
echo ""
echo -e "\033[21G\033[32mCreate configuration for a given OpenVPN key.. \033[m"
echo ""
echo ""
declare -a conf_file_arr=()
declare -a conf_name_arr=()
for _conf_file in `ls ${script_dir}/conf/server-*.conf 2>/dev/null` ; do
   conf_file_arr+=("${_conf_file}")
   _basename=$(basename $_conf_file)
   _tmp_name=${_basename%%.*}
   _tmp_name=${_tmp_name#*-}
   conf_name_arr+=("$_tmp_name")
done
if [[ ${#conf_file_arr[@]} -lt 1 ]] ; then
   fatal "NO Configuration found!"
fi
echo ""
declare -i i=0
if [[ ${#conf_file_arr[@]} -gt 1 ]] ; then
   echo ""
   echo "Which Configuration should be loaded?"
   echo ""
   for _conf_file in ${conf_file_arr[@]} ; do
      echo " [${i}] ${conf_name_arr[${i}]}"
      (( i++ ))
   done
   _OK=false
   echo
   echononl "Eingabe: "
   while ! $_OK ; do
      read _IN
      if is_number "$_IN" && [[ -n ${conf_file_arr[$_IN]} ]]; then
         conf_file=${conf_file_arr[$_IN]}
         _OK=true
      else
         echo ""  
         echo -e "\tFalsche Eingabe !"
         echo ""
         echononl "Eingabe: "
      fi
   done
else
   conf_file=${conf_file_arr[0]}
fi
echo ""
echo -e "\033[32m--\033[m"
echo ""
#---------------------------------------
#-----------------------------
# Read Configurations from $conf_file
#-----------------------------
#---------------------------------------
echononl "   Load Configuration File $(basename ${conf_file}).."
if [[ ! -f "$conf_file" ]]; then
   echo_failed
   fatal "Configuration file \033[37m\033[1m$(basename ${conf_file})\033[m not found!"
else
   source "${conf_file}" > $log_file 2>&1
   if [[ $? -eq 0 ]]; then
      echo_ok
   else
      echo_failed
      fatal "$(cat $log_file)"
   fi
fi
[[ "${SERVER_CIPHER,,}" = "none" ]] && SERVER_CIPHER="BF-CBC"
if [[ -z "$LZO_COMPRESSION" ]]; then
   LZO_COMPRESSION=true
elif $LZO_COMPRESSION ; then
   LZO_COMPRESSION=true
else
   LZO_COMPRESSION=false
fi
EASY_RSA_DIR="${OPENVPN_BASE_DIR}/easy-rsa"
echo ""
echo -e "\033[32m--\033[m"
echo ""
NEW_KEY_NAME=""
if [ -z "$NEW_KEY_NAME" ]; then
   echo "Insert an existing key name you wish to create the configuration."
   echo ""
   echo ""
   echononl "key name to create configuration: "
   read NEW_KEY_NAME
   while [ "X$NEW_KEY_NAME" = "X" ] ; do
      echo -e "\n\t\033[33m\033[1mKey name is required!\033[m\n"
      echononl "key name: "
      read NEW_KEY_NAME
   done
fi
echo ""
echo -e "\033[32m--\033[m"
echo ""
echo "Enter the password for key ${NEW_KEY_NAME}.key"
echo ""
echo -e "\033[33m\033[1mLeave empty if you don't know the password.\033[m"
echo ""
echononl "Password for key ${NEW_KEY_NAME}.key: "
read KEY_PW
if [[ -z "$(trim $KEY_PW)" ]] ; then
   KEY_PW="- Not known -"
fi
for _name in $key_names_reserverd ; do
   [[ "$_name" = "$NEW_KEY_NAME" ]] && fatal "Name '$NEW_KEY_NAME' cannot be used - its a reserved name!"
done
if [[ ! -f "${OPENVPN_BASE_DIR}/keys/${NEW_KEY_NAME}.key" ]]; then
   fatal "Key '$NEW_KEY_NAME' not found!"
fi
echo ""
echo -e "\033[32m--\033[m"
echo ""
echo "Give the username in whom's home directory the key material and"
echo "OpenVPn configuration shoud be stored"
echo ""
echo ""
if [[ -n "$DEFAULT_USER_TO_COPY_CREDENTIALS" ]] ; then
   echo -e "    Defaults to user '${DEFAULT_USER_TO_COPY_CREDENTIALS}'"
   echo ""
fi
user_name=""
if [[ -n "$DEFAULT_USER_TO_COPY_CREDENTIALS" ]] ; then
   echononl "Username: [${DEFAULT_USER_TO_COPY_CREDENTIALS}]: "
   read user_name
   if [[ "X$user_name" = "X" ]]; then
      user_name="${DEFAULT_USER_TO_COPY_CREDENTIALS}"
   fi
else
   echononl "Username: "
   read user_name
   while [[ "X$user_name" = "X" ]]; do
      echo -e "\n\t\033[33m\033[1mUsername is required!\033[m\n"
      echononl "Username: "
      read user_name
   done
fi
if getent passwd "$user_name" > /dev/null 2>&1; then
   _home_dir="$(eval echo "~$user_name")"
   if [[ ! -d "$_home_dir" ]] ; then
      fatal "User '$user_name' exists, but no home directory found!"
   fi
else
   fatal "User '$user_name' does not exist!"
fi
target_dir="${_home_dir}/VPN"
clear
echo ""
echo -e "\033[32m==========\033[m"
echo "Create OpenVPN configuration and save also key material."
echo -e "\033[32m==========\033[m"
echo ""
echo "Key Name ...............: $NEW_KEY_NAME"
echo "Key Password............: $KEY_PW"
echo "Target directory........: $target_dir"
info "Going to create configuration for key \033[37m\033[1m${NEW_KEY_NAME}.key\033[m.."
echo -n "To continue type uppercase 'YES': "
read OK
echo ""
if [[ "$OK" != "YES" ]] ; then
   fatal "Abort by user request - Answer as not 'YES'"
fi
#---------------------------------------
#-----------------------------
# Create OpenVPN configuration and save also key material.
#-----------------------------
#---------------------------------------
echo ""
# ---
# - source file vars
# ---
echononl "   Load configuration '${EASY_RSA_DIR}/vars'.."
source ${EASY_RSA_DIR}/vars > "$log_file" 2>&1
if [[ $? -eq 0 ]] ; then
   echo_ok
else
   echo_failed
   error "$(cat $log_file)"
fi
_client_conf_dir="${OPENVPN_BASE_DIR}/client-configs"
_client_conf_file="${_client_conf_dir}/${NEW_KEY_NAME}.conf"
echononl "   Create client config dir '$_client_conf_dir'.."
if [[ ! -d "$_client_conf_dir" ]]; then
   mkdir "$_client_conf_dir"  > $log_file 2>&1
   if [[ $? -eq 0 ]]; then
      echo_ok
   else
      echo_failed
      error "$(cat $log_file)"
   fi
else
   echo_skipped
fi
echononl "   Create sample client configuration ${_client_conf_file}.."
cat << EOF > "$_client_conf_file"  2> $log_file
##############################################
# Sample client-side OpenVPN 2.0 config file #
# for connecting to multi-client server.     #
#                                            #
# This configuration can be used by multiple #
# clients, however each client should have   #
# its own cert and key files.                #
#                                            #
# On Windows, you might want to rename this  #
# file so it has a .ovpn extension           #
##############################################
# Specify that we are a client and that we
# will be pulling certain config file directives
# from the server.
client
# Use the same setting as you are using on
# the server.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun
# Are we connecting to a TCP or
# UDP server?  Use the same setting as
# on the server
proto udp
# The hostname/IP and port of the server.
# You can have multiple remote entries
# to load balance between the servers.
remote $OPENVPN_SERVER $SERVER_PORT
topology subnet
# Keep trying indefinitely to resolve the
# host name of the OpenVPN server.  Very useful
# on machines which are not permanently connected
# to the internet such as laptops.
resolv-retry infinite
# Most clients don't need to bind to
# a specific local port number.
nobind
# Try to preserve some state across restarts.
persist-key
persist-tun
# Server CA
EOF
_file="${OPENVPN_BASE_DIR}/keys/ca.crt"
_found=false
while IFS='' read -r line || [[ -n $line ]]; do
   if [[ "$line" =~ "-----BEGIN" ]] ; then
      _found=true
   fi
   if $_found ; then
      echo "$line" >> "$_client_conf_file"
   fi
   if [[ "$line" =~ "-----END" ]]; then
      _found=false
   fi
done < $_file
cat << EOF >> "$_client_conf_file"  2> $log_file
# Client Certificate
EOF
_file="${OPENVPN_BASE_DIR}/keys/${NEW_KEY_NAME}.crt"
_found=false
while IFS='' read -r line || [[ -n $line ]]; do
   if [[ "$line" =~ "-----BEGIN" ]] ; then
      _found=true
   fi
   if $_found ; then
      echo "$line" >> "$_client_conf_file"
   fi
   if [[ "$line" =~ "-----END" ]]; then
      _found=false
   fi
done < $_file
cat << EOF >> "$_client_conf_file"  2> $log_file
# Client Key
EOF
_file="${OPENVPN_BASE_DIR}/keys/${NEW_KEY_NAME}.key"
_found=false
while IFS='' read -r line || [[ -n $line ]]; do
   if [[ "$line" =~ "-----BEGIN" ]] ; then
      _found=true
   fi
   if $_found ; then
      echo "$line" >> "$_client_conf_file"
   fi
   if [[ "$line" =~ "-----END" ]]; then
      _found=false
   fi
done < $_file
cat << EOF >> "$_client_conf_file"  2> $log_file
# Verify server certificate by checking
# that the certicate has the nsCertType
# field set to "server".  This is an
# important precaution to protect against
# a potential attack discussed here:
#  http://openvpn.net/howto.html#mitm
#
# To use this feature, you will need to generate
# your server certificates with the nsCertType
# field set to "server".  The build-key-server
# script in the easy-rsa folder will do this.
#
# Note!
# The option "ns-cert-type" has been deprecated since 
# version 2.4 and will be removed from later distributions.
#
# Use the modern equivalent "remote-cert-tls"
# 
;ns-cert-type server
remote-cert-tls server
# If a tls-auth key is used on the server
# then every client must also have the key.
#
# Don't forget to set the 'key-direction' Parameter if using
# Inline Key. Usualy , sever has key direction '0', while client
# has ke direction '1'.
#
key-direction 1
EOF
_file="${OPENVPN_BASE_DIR}/keys/ta.key"
_found=false
while IFS='' read -r line || [[ -n $line ]]; do
   if [[ "$line" =~ "-----BEGIN" ]] ; then
      _found=true
   fi
   if $_found ; then
      echo "$line" >> "$_client_conf_file"
   fi
   if [[ "$line" =~ "-----END" ]]; then
      _found=false
   fi
done < $_file
cat << EOF >> "$_client_conf_file"  2> $log_file
# Select a cryptographic cipher.
# If the cipher option is used on the server
# then you must also specify it here.
;cipher BF-CBC        # Blowfish (default)
;cipher AES-128-CBC   # AES
;cipher DES-EDE3-CBC  # Triple-DES
EOF
if [[ -n "$SERVER_CIPHER" ]]; then
   cat <> "$_client_conf_file" 2>> "$log_file"
cipher $SERVER_CIPHER
EOF
else
   cat <> "$_client_conf_file" 2>> "$log_file"
cipher BF-CBC
EOF
fi
cat <> "$_client_conf_file" 2>> "$log_file"
# Enable compression on the VPN link.
# Don't enable this unless it is also
# enabled in the server config file.
;comp-lzo
EOF
if $LZO_COMPRESSION ; then
   cat <> ${_client_conf_file} 2>> "$log_file"
comp-lzo
EOF
fi
cat <> ${_client_conf_file} 2>> "$log_file"
# --auth-nocache
# 
# Don't cache --askpass or --auth-user-pass username/passwords in 
# virtual memory. 
# If specified, this directive will cause OpenVPN to immediately forget 
# username/password inputs after they are used. As a result, when OpenVPN 
# needs a username/password, it will prompt for input from stdin, which may 
# be multiple times during the duration of an OpenVPN session. 
#
# When using --auth-nocache in combination with a user/password file 
# and --chroot or --daemon, make sure to use an absolute path. 
#
# 
auth-nocache
# Verbosity level.
# 0 -- quiet except for fatal errors.
# 1 -- mostly quiet, but display non-fatal network errors.
# 3 -- medium output, good for normal operation.
# 9 -- verbose, good for troubleshooting
verb 1
# Setting 'pull' on the client takes care to get the 'push' durectives
# from the server
pull
EOF
if [[ $? -eq 0 ]] ; then
   echo_ok
else
   echo_failed
   #error "$(cat $log_file)"
fi
echo ""
echononl "   Create directory '$target_dir'.."
if [[ ! -d "$target_dir" ]] ; then
   mkdir "$target_dir" > $log_file 2>&1
   if [[ $? -eq 0 ]] ; then
      echo_ok
   else
      echo_failed
      fatal "$(cat $log_file)"
   fi
else
   echo_skipped
fi
_failed=false
echononl "   Copy key material into dir '${target_dir}/${KEY_CN}-${NEW_KEY_NAME}'.."
if [[ -d "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}" ]]; then
	mv "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}" "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}.$_date" > $log_file 2>&1
	if [[ $? -ne 0 ]] ; then
		_failed=true
	fi
fi
mkdir "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}" > $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
cp -a "${OPENVPN_BASE_DIR}/keys/${NEW_KEY_NAME}.key" "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
cp -a "$_client_conf_file" "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}/client-$(basename $_client_conf_file)"
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
cp -a "$_client_conf_file" "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}/${KEY_CN}-${NEW_KEY_NAME}.ovpn"
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
cp -a "${OPENVPN_BASE_DIR}/keys/${NEW_KEY_NAME}.crt" "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
cp -a "${OPENVPN_BASE_DIR}/keys/ca.crt" "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
cp -a "${OPENVPN_BASE_DIR}/keys/ta.key" "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
cat << EOF > "${target_dir}/${KEY_CN}-${NEW_KEY_NAME}/passwd.txt"
   key...............: ${NEW_KEY_NAME}.key
   common name.......: ${KEY_CN}-${NEW_KEY_NAME}
   password..........: ${KEY_PW}
EOF
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
chown -R ${user_name}:$user_name "${_home_dir}/VPN" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
if $_failed ; then
   echo_failed
   error "$(cat $log_file)"
else
   echo_ok
fi
# - Create a folder with suffix '.tblk' containing the openvpn configuration in
# - a subfolder 'Contents/Resources' (its MAC OS specific)
# -
# - If the configuration file contains all keys/certs, only the configuration file
# - with its suffix '.ovpn' is needed.
# - 
echononl "   Create zip archive '${KEY_CN}-${NEW_KEY_NAME}.tblk.zip' for MAC OS .."
target_macos_tblk_dir="${target_dir}/${KEY_CN}-${NEW_KEY_NAME}/${KEY_CN}-${NEW_KEY_NAME}.tblk"
mkdir "$target_macos_tblk_dir" > $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
mkdir -p "${target_macos_tblk_dir}/Contents/Resources" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
cp -a "$_client_conf_file" "${target_macos_tblk_dir}/Contents/Resources/config.ovpn" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
cd ${target_dir}/${KEY_CN}-${NEW_KEY_NAME} >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
chown -R ${user_name}:$user_name "$target_macos_tblk_dir" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
zip -r "${KEY_CN}-${NEW_KEY_NAME}.tblk.zip" \
   "${KEY_CN}-${NEW_KEY_NAME}.tblk" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
chown ${user_name}:$user_name "${KEY_CN}-${NEW_KEY_NAME}.tblk.zip" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
rm -r "${target_macos_tblk_dir}" >> $log_file 2>&1
if [[ $? -ne 0 ]] ; then
   _failed=true
fi
if $_failed ; then
   echo_failed
   error "$(cat $log_file)"
else
   echo_ok
fi
info "Key material and OpenVPN for key \033[37m\033[1m${NEW_KEY_NAME}.key\033[m is stored at '${_home_dir}/VPN'"
clean_up 0