#!/bin/bash
. /etc/openvpn/login/config.sh

# Use a fixed IP or the server's public IP
server_ip="SERVER_IP"
datenow=$(date +"%Y-%m-%d %T")
tm=$(date +%s)
dt=$(date +'%Y-%m-%d %H:%M:%S')
timestamp=$(date +'%FT%TZ')

# 1. Check if user is already marked online using COUNT (Faster)
# We use -N to remove headers and -B for batch mode
check_count=$(mysql -u "$USER" -p"$PASS" -D "$DB" -h "$HOST" -N -B -e "SELECT COUNT(*) FROM bandwidth_logs WHERE username='$common_name' AND status='online'")

if [ "$check_count" -gt 0 ]; then
    # 2. Update existing session
    mysql -u "$USER" -p"$PASS" -D "$DB" -h "$HOST" -e "UPDATE bandwidth_logs SET server_ip='$trusted_ip', server_port='$trusted_port', timestamp='$timestamp', ipaddress='$trusted_ip:$trusted_port', time_in='$tm', since_connected='$time_ascii', bytes_received='$bytes_received', bytes_sent='$bytes_sent' WHERE username='$common_name' AND status='online'"
else
    # 3. Insert new session
    mysql -u "$USER" -p"$PASS" -D "$DB" -h "$HOST" -e "INSERT INTO bandwidth_logs (server_ip, server_port, timestamp, ipaddress, since_connected, username, bytes_received, bytes_sent, time_in, status, time) VALUES ('$trusted_ip','$trusted_port','$timestamp','$trusted_ip:$trusted_port','$time_ascii','$common_name','$bytes_received','$bytes_sent','$dt','online','$tm')"
fi

# 4. Update main user table
mysql -u "$USER" -p"$PASS" -D "$DB" -h "$HOST" -e "UPDATE users SET is_connected='1', device_connected='1', active_address='$server_ip', active_date='$datenow' WHERE user_name='$common_name'"