#!/bin/bash

# Files and Directories
OPENVPN_CPE_INC="/etc/openvpn/cpe.inc"
OPENVPN_KEY_DIR="/etc/openvpn/keys"

manager_vpn_start () {
    local SERVER=$1
    local PORTCOUNT=0
    shift

    SERIAL=`admin-helper get-config "/etc/oe-release" "Serial"`
    #SERVER=`admin-helper get-config "/etc/branding.conf" "VPNServer"`

    #If we don't find the expected files in the keys folder
    #might as well remove everything that's there
    if [ ! -s /etc/openvpn/keys/cpe-${SERIAL}.key ]; then
        rm -rf /etc/openvpn/keys/*
    fi
    if [ ! -s /etc/openvpn/keys/cpe-${SERIAL}.crt ]; then
        rm -rf /etc/openvpn/keys/*
    fi
    if [ ! -s /etc/openvpn/keys/ca.crt ]; then
        rm -rf /etc/openvpn/keys/*
    fi

    # Download the VPN keys if required
    if [ ! -f /etc/openvpn/keys/cpe-${SERIAL}.key ]; then
        admin-helper cpe-vpnkeys
        if [ "$?" != "0" ]; then
            echo "Failed to get VPN keys" | logger -p local1.err -t manager.vpn-start
            return 1
        fi
    fi

    # Erase the existing CPE configuration
    rm -f ${OPENVPN_CPE_INC}

    # Write the port list to the CPE configuration
    while [ "$#" != "0" ]; do
        PORTCOUNT=$((PORTCOUNT + 1))
        echo "remote $SERVER $1"
        shift
    done >> ${OPENVPN_CPE_INC}

    if [ "$PORTCOUNT" -gt "1" ]; then
        echo "remote-random" >> ${OPENVPN_CPE_INC}
    fi

    # Write the certificate and key file to the CPE configuration
    echo "cert keys/cpe-$SERIAL.crt" >> ${OPENVPN_CPE_INC}
    echo "key keys/cpe-$SERIAL.key" >> ${OPENVPN_CPE_INC}

    chown root:root ${OPENVPN_KEY_DIR}
    chmod 0700 ${OPENVPN_KEY_DIR}

    /etc/init.d/openvpn start | logger -p local1.info -t manager.vpn-start

    return 0
}
