Q="## OpenVPN Installer && and config-file DeGenerator\r\n## From VPS-server.RU with love :o)"
V="## Version 0.5 Beta. Support@vps-server.ru"
BOXES=$(which boxes |xargs |wc -l)

usage()
{
	local BP
	BP=$(which bash)
	msgE "Error: command is empty!"
	msgW "$Q"
	msgW "$V"
	msgW "Please use it now:"
	msgW "	for install or reconfigure OpenVPN server use: ${BP} ${0%/*} --install|-i"
	msgW "	for list OpenVPN clients use: ${BP} ${0%/*} --list|-L"
	msgW "	for revoke client certificate use: ${BP} ${0%/*} --revoke|-R USERNAME"	
	msgW "	lease use: ${BP} ${0##*/} USERNAME [OpenVPN IP]"
	msgW "	example: ${BP} ${0##*/} --list"
	msgW "	example: ${BP} ${0##*/} zalmanzon 93.81.119.119"
	msgW "	example: ${BP} ${0##*/} --revoke zalmanzon"	
}

setIptablesOpenVZ()
{

IPT=$(which iptables)

cat <<EOF > $2
#!/bin/bash

$IPT -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
$IPT -A FORWARD -s 10.8.0.0/24 -j ACCEPT
$IPT -A FORWARD -j REJECT
$IPT -t nat -A POSTROUTING  -s 10.8.0.0/24 -o venet0 -j SNAT --to-source $1
EOF

echo '@reboot root  /bin/sleep 20; /bin/bash /root/reboot.sh' > /etc/cron.d/openvpn
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf
sysctl -p
}

crFileOvpn() 
{
local D
local T
# D=$(date +'%F %T'); 
#if [ $BOXES -eq 1 ]; then
#	T=$(echo -e "File $F generated $D\r\nvia $Q\r\n\t $V :o)" | boxes -s 80x5 -d shell )
#else
T=$(echo -e "# File $F generated $(date +'%F %T') via \r\n$Q \r\n$V :o)" )
#fi

cat <<EOF > $F
###
$T
#
# daemon # <<<- unRemark this option for Linux OpenVPN
remote $2
dhcp-option DNS 8.8.4.4
dhcp-option DNS 208.67.220.220
redirect-gateway def1
server-poll-timeout 5
client
ifconfig-nowarn
sndbuf 524288
rcvbuf 524288
push "sndbuf 524288"
push "rcvbuf 524288"
remote-cert-tls server
EOF
}

GetCertTxt() {
	tmpFile=$(mktemp /tmp/XXXXXXXXX.tmp)
	echo "<$2>" > $tmpFile; cat $1 >> $tmpFile; echo "</$2>"  >> $tmpFile
	cat $tmpFile
	rm -f $tmpFile
}


DebianInstall() 
{
    apt update; apt install -y openvpn easy-rsa dialog boxes
    # create new server config
    cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /tmp/
    gunzip /tmp/server.conf.gz
    mv /tmp/server.conf /etc/openvpn/openvpn.conf
}

FreeBSDInstall() 
{
	pkg install -y openvpn easy-rsa
	sysrc openvpn_enable="YES"
	mkdir -p /usr/local/etc/openvpn
	cp /usr/local/share/examples/openvpn/sample-config-files/server.conf /usr/local/etc/openvpn/openvpn.conf
	cp -r /usr/local/share/easy-rsa /usr/local/etc/openvpn/easy-rsa
	service openvpn start
}

setVariables()
{
    echo 'set_var EASYRSA_REQ_COUNTRY    "RU"'
    echo 'set_var EASYRSA_REQ_PROVINCE   "37 Region"'
    echo 'set_var EASYRSA_REQ_CITY       "Ivanovo City"'
    echo 'set_var EASYRSA_REQ_ORG        "VSP-server.ru"'
    echo 'set_var EASYRSA_REQ_EMAIL      "support@vps-server.ru"'
    echo 'set_var EASYRSA_REQ_OU         "IT Community"'
}

ConfigureOvpnServer() {
	local EP=$1 varfile
	# edit variables to easy RSA
	cp $EP/vars.example $EP/vars
	varfile=$(mktemp /tmp/XXXXXXXXX.tmp)
	$(setVariables > $varfile ); mcedit $varfile; cat $varfile  >>  $EP/vars
	# goto easyRSA
	cd $EP; ./easyrsa init-pki
	# CA
	./easyrsa build-ca nopass
	ln -s /usr/share/easy-rsa/pki/ca.crt  /etc/openvpn/ca.crt
	# server key
	./easyrsa gen-req server nopass
	ln -s /usr/share/easy-rsa/pki/private/server.key /etc/openvpn/server.key
	# server crt
	./easyrsa sign-req server server
	ln -s /usr/share/easy-rsa/pki/issued/server.crt /etc/openvpn/
	# Diffie-Hellman key
	./easyrsa gen-dh
	ln -s /usr/share/easy-rsa/pki/dh.pem /etc/openvpn/dh2048.pem
	# ta.key
	openvpn --genkey --secret ta.key
	ln -s /usr/share/easy-rsa/ta.key /etc/openvpn/ta.key
}

FreeBSDKeygen() 
{
	# set -x
	OVPN_CONF=/usr/local/etc/openvpn/openvpn.conf
	if [ ! -f $OVPN_CONF ]; then
		msgE "openvpn.conf - file $OVPN_CONF not found!"; exit 1
	fi
	
	ERSA=$(which easy-rsa)
	
	CheckCERT=$( cat $P/pki/index.txt | grep "^V" |  grep "/CN=$1$"| awk '{print $2}' | sed -r 's/([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})Z/\3\/\2\/\1 \4:\5:\6 /g')
	if [ "$CheckCERT" != '' ]; then
		dialog --title "Revoke and issue this certificate now?" --backtitle "OpenVPN server $distr"  --yesno "\nA certificate valid until $CheckCERT was found for the '$1' \n\n Do you want to issue a new certificate now?" 9 50 ; response=$?
		if [ $response -eq 0 ]; then
			echo "Revoke certificate for '$1'!"
			cd $P;
			echo -e "yes\n" |  $ERSA revoke $1
		else
			exit 0;
		fi
	fi

    [ "$2" != '' ] && REMOTEIP=$2 || REMOTEIP=$(fetch https://chast.in/ip.php -q -o /tmp/ip |cat /tmp/ip )
    [ ${0%/*} == ${0##*/} ] && F="./$1.ovpn" || F="${0%/*}/$1.ovpn"; cd $P
	echo -e "Genering OpenVpn config for client name '$1'"
    $ERSA build-client-full $1 nopass;  crFileOvpn $F $REMOTEIP
	cat $OVPN_CONF |grep -vE '(^#|^$|^;|^log|^status|^ifconfig-pool-persist|^ca |^cert |^key |^dh |^push |^crl-verify |^tls-auth |^topology |^server |^client-config-dir |^tun-mtu |^sndbuf |^rcvbuf |^explicit-exit-notify )' >> $F
	#echo -e $(GetCertTxt $P/pki/issued/$1.crt cert) >> $F
	echo "<cert>" >> $F; cat $P/pki/issued/$1.crt >> $F; echo "</cert>" >> $F
	echo "<key>" >> $F; cat $P/pki/private/$1.key >> $F; echo "</key>" >> $F
	echo "<ca>" >> $F; cat $P/pki/ca.crt >> $F;  echo "</ca>" >> $F
	
	TLS_ENABLED=$(cat $OVPN_CONF | egrep '^[^#]*tls-auth')
	if [ "$TLS_ENABLED" != '' ]; then
		echo "<tls-auth>" >> $F; cat /usr/local/etc/openvpn/keys/ta.key >> $F;  echo "</tls-auth>" >> $F
		#echo "key-direction 1" >> $F
		sed -i '' -e 's/key-direction 0/key-direction 1/g' $F
	fi
}

DebianKeygen() 
{
	if [ ! -f $OVPN_CONF ]; then
		msgE "openvpn.conf - file $OVPN_CONF not found!"
		exit 0
	fi

	CheckCERT=$( cat $P/pki/index.txt | grep "^V" |  grep "/CN=$1$"| awk '{print $2}' | sed -r 's/([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})Z/\3\/\2\/\1 \4:\5:\6 /g')
	if [ "$CheckCERT" != '' ]; then
		dialog --title "Revoke and Reissue $1 certificate now?" --backtitle "OpenVPN server $distr"  --yesno "\nA certificate valid until $CheckCERT was found for the '$1' \n\nDo you want re-issue this cert now?" 9 50 ; response=$?
		if [ $response -eq 0 ]; then
			echo "Revoke certificate for '$1'!"
			cd $P;
			echo -e "yes\n" |  ./easyrsa revoke $1
		else
			exit 0;
		fi
	fi
	echo "Genering new OpenVPN config for username '$1'"
	cd $P;	source ./vars ; ./easyrsa build-client-full $1 nopass; crFileOvpn $F $REMOTEIP
	cat $OVPN_CONF |grep -v -OE '(^#|^$|^;|^log|^status|^ifconfig-pool-persist|^ca |^cert |^key |^dh |^push |^crl-verify |^tls-auth |^topology |^server )' >> $F
	echo "<cert>" >> $F; cat $P/pki/issued/$1.crt >> $F; echo "</cert>" >> $F
	echo "<key>" >> $F; cat $P/pki/private/$1.key >> $F; echo "</key>" >> $F
	echo "<ca>" >> $F; cat $P/pki/ca.crt >> $F;  echo "</ca>" >> $F
	TLS_ENABLED=$(cat $OVPN_CONF | egrep '^[^#]*tls-auth')
	if [ "$TLS_ENABLED" != '' ]; then
		echo "<tls-auth>" >> $F; cat /etc/openvpn/ta.key >> $F;  echo "</tls-auth>" >> $F
		# echo "key-direction 1" >> $F
		sed -i '' -e 's/key-direction 0/key-direction 1/g' $F
	fi
}

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'
msgE(){ printf "${RED}$1${NC}\n";}
msgW(){ printf "${GREEN}$1${NC}\n";}

# echo  "\n$Q\n\t$V\n\t"

curPwd=$(realpath ./ )
Reconfigure=0
P=$(whereis easy-rsa | grep "easy-rsa" | awk '{print $2}' | xargs )
O=$(whereis openvpn | grep "openvpn" | awk '{print $2}' | xargs )

# Check OS
#set -x
if [[ "$OSTYPE" == *"linux-gnu"* ]]; then
	distr=$(cat /etc/*release | grep 'HOME_URL=' | grep -oE 'debian|centos|virtuozzo|ubuntu')
elif [[ "$OSTYPE" == *"freebsd"* || "$OSTYPE" == *"FreeBSD"*  ]]; then
    distr='freebsd'
    P="/usr/local/etc/openvpn/easy-rsa"
else
    # Unknown.
    echo "Sorry! UnSupported OS. Exiting"
    echo "Please send email support@vps-server.ru"
    exit 0;
fi

# set +x

while [ -z "$P" ] || [ -z "$O" ];  do
  case $distr in
        debian | ubuntu )
		dialog --title "Install openvpn" --backtitle "OpenVPN server install script for $distr"  --yesno "\nOpenvpn server not found! \n\nCan you install openvpn server now?" 9 50 ; response=$?
		if [[ $response -eq 0 ]]; then
			DebianInstall
			Reconfigure=1
		else
			exit 0;
		fi
	;;
	centos )
		dialog --title "Install openvpn" --backtitle "OpenVPN server install script for $distr"  --yesno "\nOpenvpn server not found! \n\nCan you install openvpn server now?" 9 50 ; response=$?
                if [[ $response -eq 0 ]]; then
			yum update; yum install -y openvpn easy-rsa
 			Reconfigure=1
		else
			exit 0;
		fi
	;;
	freebsd ) 
		dialog --title "Install openvpn" --backtitle "OpenVPN server install script for $distr"  --yesno "\nOpenvpn server not found! \n\nCan you install openvpn server now?" 9 50 ; response=$?
		if [[ $response -eq 0 ]]; then
			FreeBSDInstall
			Reconfigure=1
		else
            exit 0;
        fi

	;;

        *)
        echo -n "unknown"
        exit 0
        ;;
  esac

  P=$(whereis easy-rsa | grep "easy-rsa" | awk '{print $2}' | xargs )
  O=$(whereis openvpn | grep "openvpn" | awk '{print $2}' | xargs )
done

if [ $Reconfigure -eq 1 ] ;then
	ConfigureOvpnServer $P
fi

# find openvpn process
# OVPN_CONF=$(ps ax | grep openvpn.conf | grep "\-\-config" | sed "s/.*--config //" | awk '{print $1}')

OVPN_CONF=$(ps ax | grep -oE '\-\-config ([^-\20]*)' | grep 'openvpn.conf' | sed 's/--config//g')
if [ -z $OVPN_CONF ]; then
	msgE "Error: OpenVPN process not found!"; 
	#exit 1;
fi
if [ "$P" == "" ];then
	echo "Error: Easy RSA not found!"; exit 1;
fi

if [ $# != 0  ] && [ "$1" != '' ]; then

	if [ "$1" == '--revoke' ] || [ "$1" == '-R' ] ; then
		if [ ! -z "$2" ]; then
			Revoke=1
		else
			msgE "Error: OpenVPN client is empty!"; exit 1;
		fi
	fi

	if [ "$1" == '--install' ] || [ "$1" == '-I' ]; then
		Reconfigure=1
	fi

	if [ "$1" == '--list' ] || [ "$1" == '-L' ] ; then
		List=1
	fi

	[ ${0%/*} == ${0##*/} ] && F="./$1.ovpn" || F="${0%/*}/$1.ovpn"

	case $distr in

	debian | ubuntu )
    	if [[ $Reconfigure -eq 1 ]]; then
        	ConfigureOvpnServer
		service openvpn restart
		setIptablesOpenVZ
        else
		[ "$2" != '' ] && REMOTEIP=$2 || REMOTEIP=$(wget https://chast.in/ip.php -q -O /tmp/ip; cat /tmp/ip)
		DebianKeygen $1 $2
		mv $F $curPwd/
        fi
	;;

	freebsd )
	if [[ $List -eq 1 ]]; then
		# cat $P/pki/index.txt | grep "^V" |  grep "/CN=$1$"| awk '{print $2}' | sed -r 's/([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})Z/\3\/\2\/\1 \4:\5:\6 /g'
		echo "+---------------------------------------+"
		echo "|  datatime of end |  certificate name	|"
		echo "+---------------------------------------+"
		cat $P/pki/index.txt | grep '^V' | sed 's/\/CN=//' | sed -r 's/([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})Z/\3\/\2\/\1 \4:\5:\6 /g' |  awk '{ printf "|%s %s | %-12s	|\n", $2, $3, $6}'
		echo "+---------------------------------------+"
		exit 0
	fi
    	if [[ $Revoke -eq 1 ]]; then
    		echo $P
		dialog --title "Revoke this certificate now?" --backtitle "OpenVPN server $distr"  --yesno "\nRevoke $2 certificate now?" 9 50 ; response=$?
		if [ $response -eq 0 ]; then
			echo "Revoke certificate for '$2'!"
			cd $P;
			echo -e "yes\n" |  ./easyrsa.real revoke $2
			exit 0
		else
			exit 0
		fi
	fi

    	if [[ $Reconfigure -eq 1 ]]; then
        	ConfigureOvpnServer
        	exit 0
        else
		[ "$2" != '' ] && REMOTEIP=$2 || REMOTEIP=$(fetch https://chast.in/ip.php -q -o /tmp/ip; cat /tmp/ip)
		FreeBSDKeygen $1 $2
		mv $F $curPwd/
        fi
	;;
	centos )
	echo -n "centos"
	;;

	*)
	echo -n "unknown"
	exit 0
	;;
	esac
	echo
	echo
	echo "You can move file $F to your local computer and use it:"
	echo "In Linux: openvpn --config $1.ovpn"
	echo "In Windows you can import file $F in openvpn Desktop Client"
	echo "In MAC  you can import file $F to https://tunnelblick.net/ util"
	echo
else
	usage
fi
exit
