#!/bin/bash

# Ensure a username is passed
if [ -z "$1" ]; then
  echo "Error: No username provided."
  exit 1
fi

USERNAME="$1"  # Take the username as the first argument

# MySQL Database connection details
DB_HOST="172.24.250.97"
DB_USER="vignesh"
DB_PASSWORD="12345678"
DB_NAME="wire-client"

# Query the database to get the IP address for the given username
IP=$(mysql -h "$DB_HOST" -u "$DB_USER" -p"$DB_PASSWORD" -D "$DB_NAME" -se "SELECT ipaddress FROM usermaster WHERE username = '$USERNAME';")

# Ensure the IP address is retrieved
if [ -z "$IP" ]; then
  echo "Error: No IP address found for username: $USERNAME."
  exit 1
fi

echo "IP Address found for $USERNAME: $IP"

PRIVATE_KEY_PATH="/etc/wireguard/clients/$USERNAME.key"
PUBLIC_KEY_PATH="/etc/wireguard/clients/$USERNAME.pub"
CONFIG_FILE_PATH="/etc/wireguard/$USERNAME.conf"

# Ensure the directory exists
sudo mkdir -p /etc/wireguard/clients/

# Generate the private key
PRIVATE_KEY=$(wg genkey)

# Save the private key to the specified location
echo "$PRIVATE_KEY" | sudo tee "$PRIVATE_KEY_PATH" > /dev/null

# Generate the public key from the private key
PUBLIC_KEY=$(echo "$PRIVATE_KEY" | wg pubkey)

# Save the public key to the specified location
echo "$PUBLIC_KEY" | sudo tee "$PUBLIC_KEY_PATH" > /dev/null

# Output the paths of the generated keys
echo "Private key saved to: $PRIVATE_KEY_PATH"
echo "Public key saved to: $PUBLIC_KEY_PATH"

# Extract the last octet from the retrieved IP address (e.g., 172.24.250.3 -> 3)
LAST_OCTET=$(echo "$IP" | awk -F '.' '{print $4}')

# Ensure the extracted part is a valid number
if ! [[ "$LAST_OCTET" =~ ^[0-9]+$ ]]; then
  echo "Error: Invalid IP address format. Please provide a valid IP address (e.g., 10.10.10.x)."
  exit 1
fi

# Check if the configuration file exists, if not create it
if [ ! -f "$CONFIG_FILE_PATH" ]; then
  sudo touch "$CONFIG_FILE_PATH"
fi

# Check if the Peer section for this username already exists in the config file
if grep -q "PublicKey = $(sudo cat "$PUBLIC_KEY_PATH")" "$CONFIG_FILE_PATH"; then
  echo "Peer with PublicKey already exists in $CONFIG_FILE_PATH. Skipping..."
else
  # Add the [Peer] section to the config file
  echo -e "\n[Peer]" | sudo tee -a "$CONFIG_FILE_PATH" > /dev/null
  echo -e "PublicKey = $(sudo cat "$PUBLIC_KEY_PATH")" | sudo tee -a "$CONFIG_FILE_PATH" > /dev/null
  echo -e "AllowedIPs = 10.10.10.${LAST_OCTET}/32" | sudo tee -a "$CONFIG_FILE_PATH" > /dev/null

  echo "Peer configuration added to: $CONFIG_FILE_PATH"
fi

# Create the client configuration file
echo -e "[Interface]\nPrivateKey = $(sudo cat "$PRIVATE_KEY_PATH")\nAddress = 10.10.10.${LAST_OCTET}/32\nDNS = 172.24.255.254\n\n[Peer]\nPublicKey = $(sudo cat /etc/wireguard/clients/$USERNAME.pub)\nAllowedIPs = 10.10.10.0/24, 172.24.0.0/16\nEndpoint = wire1.inout.co.in:51820\n" | sudo tee /etc/wireguard/${USERNAME}.conf > /dev/null

echo "Client configuration file saved to: /etc/wireguard/${USERNAME}.conf"

# Insert data into the wireguard_config table
mysql -h "$DB_HOST" -u "$DB_USER" -p"$DB_PASSWORD" -D "$DB_NAME" -e "
INSERT INTO peer (username, public_key, allowed_ips, endpoint) 
VALUES ('$USERNAME', '$PUBLIC_KEY', '10.10.10.0/24, 172.24.0.0/16', 'wire1.inout.co.in:51820');
"

echo "Configuration for $USERNAME inserted into wireguard_config table."

