#!/bin/sh

. $TS_GLOBAL

case "$1" in  
init)
    if ! pkg_initialized $PACKAGE; then
	pkg_set_init_flag $PACKAGE
	/sbin/modprobe tun >/dev/null 2>&1
	if [ ! -z "$OPENVPN_SERVER" ]; then
	    if [ ! -f /etc/openvpn/client.p12 ]; then
		for config in "$STORAGE_CONFIG1" "$STORAGE_CONFIG2" "$STORAGE_CONFIG3" "$STORAGE_CONFIG4" "$STORAGE_CONFIG5" "$STORAGE_CONFIG6" "$STORAGE_CONFIG7" "$STORAGE_CONFIG8"
		do
		    filename=$config/thinstation.$PREFIX/client.p12
		    if [ -e "$filename" ] ; then
			    cp -f $filename /etc/openvpn/client.p12 > /dev/null 2>&1
			    cleanup
			    echo_log "Openvpn keys read from $config"
		    fi
		done
	    fi
	    if [ -e /etc/openvpn/client.p12 ]; then
		cd /etc/openvpn
		echo -e "s/\$OPENVPN_SERVER/$OPENVPN_SERVER/g\n \
			 s/\$OPENVPN_PORT/$OPENVPN_PORT/g\n \
			 s/\$OPENVPN_PROTO/$OPENVPN_PROTO/g" >> /tmp/script
		cat client.tpl | sed -f /tmp/script  > client.conf
		rm /tmp/script
		if  [ ! -z "$OPENVPN_PROXY" ] && [ ! -z "$OPENVPN_PROXY_PORT" ]; then
		    echo ${OPENVPN_PROXY_TYPE}-proxy $OPENVPN_PROXY $OPENVPN_PROXY_PORT >> /etc/client.conf
		    echo ${OPENVPN_PROXY_TYPE}-proxy-retry >> /etc/client.conf
		fi
		/bin/openvpn --daemon --config /etc/openvpn/client.conf --cd /etc/openvpn
	    fi
	fi
    fi
    ;;
help)
    echo "Usage: $0 init"
    ;;
  *)
    exit 1
    ;;
esac

exit 0
