#!/bin/bash

#
# Generate OpenVPN users via google authenticator
#

if ! source "$OPENVPN/ovpn_env.sh"; then
    echo "Could not source $OPENVPN/ovpn_env.sh."
    exit 1
fi

if [ "x$OVPN_OTP_AUTH" != "x1" ]; then
    echo "OTP authentication not enabled, please regenerate configuration using -2 flag"
    exit 1
fi

if [ -z $1 ]; then
    echo "Usage: ovpn_otp_user USERNAME"
    exit 1
fi

# Ensure the otp folder is present
[ -d /etc/openvpn/otp ] || mkdir -p /etc/openvpn/otp

# Binary is present in image, save an $user.google_authenticator file in /etc/openvpn/otp
if [ "$2" == "interactive" ]; then
    # Authenticator will ask for other parameters. User can choose rate limit, token reuse policy and time window policy
    # Always use time base OTP otherwise storage for counters must be configured somewhere in volume
    google-authenticator --time-based --force -l "${1}@${OVPN_CN}" -s /etc/openvpn/otp/${1}.google_authenticator
else
    google-authenticator --time-based --disallow-reuse --force --rate-limit=3 --rate-time=30 --window-size=3 \
        -l "${1}@${OVPN_CN}" -s /etc/openvpn/otp/${1}.google_authenticator
fi