#!/bin/bash

# Copyright (C) 2014 Balena Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

function cleanup() {
	if [[ $? -gt 0 ]]; then
 		cat </tmp/$PPID.tmp >>/tmp/stderr-$PPID.log  		
	fi
	rm /tmp/$PPID.tmp
}
trap 'cleanup' EXIT

VPN_INSTANCE_ID=$1
VPN_API_PORT=$2

if [[ -z "${bytes_received}" ]]; then
	curl -s -X POST -H 'Content-type: application/json' -d @- "http://127.0.0.1:${VPN_API_PORT}/api/v2/${VPN_INSTANCE_ID}/clients" 2>/tmp/$PPID.tmp <<-EOF &
{
	"common_name": "$common_name"
}
EOF
else
	curl -s -X DELETE -H 'Content-type: application/json' -d @- "http://127.0.0.1:${VPN_API_PORT}/api/v2/${VPN_INSTANCE_ID}/clients" 2>/tmp/$PPID.tmp <<-EOF &
{
	"common_name": "$common_name",
	"bytes_received": $bytes_received,
	"bytes_sent": $bytes_sent,
	"time_duration": $time_duration
}
EOF
fi
