#!/bin/bash

# GNX-WEB Key Update Script
# Regenerates and updates SECRET_KEY and INTERNAL_API_KEY

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Get script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BACKEND_DIR="$SCRIPT_DIR/backEnd"

# Function to generate secure random key
generate_secret_key() {
    python3 -c "import secrets; print(secrets.token_urlsafe($1))" 2>/dev/null || \
    openssl rand -base64 $((($1 * 3) / 4)) | tr -d '\n' | head -c $1
}

echo -e "${BLUE}=========================================="
echo "GNX-WEB Key Update Script"
echo "==========================================${NC}"
echo ""

# Check if .env file exists
if [ ! -f "$BACKEND_DIR/.env" ]; then
    echo -e "${RED}Error: .env file not found at $BACKEND_DIR/.env${NC}"
    echo -e "${YELLOW}Please run deploy.sh first or create .env manually${NC}"
    exit 1
fi

# Generate new keys
echo -e "${BLUE}Generating new secure keys...${NC}"
SECRET_KEY=$(generate_secret_key 50)
INTERNAL_API_KEY=$(generate_secret_key 32)

# Update .env file
echo -e "${BLUE}Updating .env file...${NC}"
sed -i "s|^SECRET_KEY=.*|SECRET_KEY=$SECRET_KEY|" "$BACKEND_DIR/.env"
sed -i "s|^INTERNAL_API_KEY=.*|INTERNAL_API_KEY=$INTERNAL_API_KEY|" "$BACKEND_DIR/.env"
echo -e "${GREEN}✓ Updated SECRET_KEY${NC}"
echo -e "${GREEN}✓ Updated INTERNAL_API_KEY${NC}"

# Update nginx config if it exists
if [ -f "/etc/nginx/sites-available/gnxsoft" ]; then
    echo -e "${BLUE}Updating nginx configuration...${NC}"
    escaped_key=$(echo "$INTERNAL_API_KEY" | sed 's/[[\.*^$()+?{|]/\\&/g')
    sudo sed -i "s|set \$api_key \".*\";|set \$api_key \"$escaped_key\";|g" /etc/nginx/sites-available/gnxsoft
    echo -e "${GREEN}✓ Updated nginx config with INTERNAL_API_KEY${NC}"
    
    # Test nginx configuration
    if sudo nginx -t >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Nginx configuration is valid${NC}"
        echo -e "${YELLOW}Reload nginx with: sudo systemctl reload nginx${NC}"
    else
        echo -e "${RED}✗ Nginx configuration has errors${NC}"
        echo -e "${YELLOW}Please check manually: sudo nginx -t${NC}"
    fi
else
    echo -e "${YELLOW}⚠ Nginx config not found. Update manually if needed.${NC}"
fi

echo ""
echo -e "${GREEN}=========================================="
echo "Keys Updated Successfully!"
echo "==========================================${NC}"
echo ""
echo -e "${BLUE}New Keys:${NC}"
echo -e "${GREEN}SECRET_KEY: ${SECRET_KEY:0:30}...${NC}"
echo -e "${GREEN}INTERNAL_API_KEY: ${INTERNAL_API_KEY:0:30}...${NC}"
echo ""
echo -e "${YELLOW}Note: You may need to restart services for changes to take effect${NC}"
echo -e "${YELLOW}Run: ./restart-services.sh${NC}"
echo ""

