#!/bin/bash

# Define variables
NGINX_CONF_DIR="/etc/nginx/sites-available"
NGINX_ENABLED_DIR="/etc/nginx/sites-enabled"
CONF_FILE="api.cemcoe.com"
CONF_PATH="$NGINX_CONF_DIR/$CONF_FILE"
LINK_PATH="$NGINX_ENABLED_DIR/$CONF_FILE"
PROXY_TARGET="http://127.0.0.1:3000/"

# Create Nginx configuration file
echo "Configuring Nginx for api.cemcoe.com..."
sudo tee "$CONF_PATH" <<EOL

server {
    listen 80;
    server_name api.cemcoe.com;

    client_max_body_size 100M;

    # Timeout settings for download large file
    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;

    location / {
      proxy_pass $PROXY_TARGET;
      # get ip
      proxy_set_header Host \$host;
      proxy_set_header X-Real-IP \$remote_addr;
      proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto \$scheme;
      # largefile
      proxy_buffering off; # Disable buffering for this location
    }
}
EOL

# Create symbolic link to enable configuration
echo "Linking configuration to $NGINX_ENABLED_DIR..."
sudo ln -sf "$CONF_PATH" "$LINK_PATH"

# Test Nginx configuration syntax
echo "Testing Nginx configuration..."
sudo nginx -t
if [ $? -ne 0 ]; then
    echo "Nginx configuration test failed. Please check the configuration file."
    exit 1
fi

# Restart Nginx service
echo "Restarting Nginx to apply changes..."
sudo systemctl restart nginx
if [ $? -eq 0 ]; then
    echo "Nginx restarted successfully."
else
    echo "Failed to restart Nginx. Please check the service status."
    exit 1
fi

echo "Nginx has been configured successfully for api.cemcoe.com."