#!/usr/bin/env bash
#
# update-nginx-codenames.sh - Update nginx codenames configuration
#
# Automatically generates nginx config snippet with available codenames
# for old format pool access.
#
# Usage: update-nginx-codenames.sh [publish_base] [output_file]
#
# Examples:
#   ./update-nginx-codenames.sh /opt/repo/public /etc/nginx/conf.d/repo-codenames.conf
#   ./update-nginx-codenames.sh  # Uses defaults
#

set -e
set -o pipefail

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

# Defaults
PUBLISH_BASE="${1:-/opt/repo/public}"
OUTPUT_FILE="${2:-/etc/nginx/conf.d/repo-codenames.conf}"

# Temporary file
TEMP_FILE=$(mktemp)

echo -e "${BLUE}=== Updating nginx codenames configuration ===${NC}"
echo "Publish base: $PUBLISH_BASE"
echo "Output file: $OUTPUT_FILE"
echo ""

# Check if publish_base exists
if [ ! -d "$PUBLISH_BASE" ]; then
    echo -e "${RED}Error: Publish base doesn't exist: $PUBLISH_BASE${NC}"
    exit 1
fi

# Scan for codenames
echo -e "${YELLOW}→ Scanning for codenames...${NC}"
codenames=()
for dir in "$PUBLISH_BASE"/*; do
    if [ -d "$dir" ]; then
        dirname=$(basename "$dir")
        # Skip special directories
        if [ "$dirname" = "dists" ] || [ "$dirname" = "beta" ] || [ "$dirname" = "test" ]; then
            continue
        fi
        # Check if it looks like a codename (has dists subdirectory)
        if [ -d "$dir/dists" ]; then
            codenames+=("$dirname")
        fi
    fi
done

if [ ${#codenames[@]} -eq 0 ]; then
    echo -e "${YELLOW}⚠️  No codenames found in $PUBLISH_BASE${NC}"
    echo "Nothing to update"
    exit 0
fi

echo "Found ${#codenames[@]} codenames:"
for cn in "${codenames[@]}"; do
    echo "  - $cn"
done

# Generate nginx configuration
echo ""
echo -e "${YELLOW}→ Generating nginx configuration...${NC}"

cat > "$TEMP_FILE" <<'EOF'
# Auto-generated nginx configuration for repository codenames
# Generated by: update-nginx-codenames.sh
# DO NOT EDIT MANUALLY - will be overwritten
#
# This file is included in main nginx config to provide dynamic codename list
# for old format APT pool access.
#
EOF

echo "# Generated: $(date)" >> "$TEMP_FILE"
echo "# Codenames: ${codenames[*]}" >> "$TEMP_FILE"
echo "" >> "$TEMP_FILE"

# Generate try_files list (newest first - reverse sort by name)
sorted_codenames=($(printf '%s\n' "${codenames[@]}" | sort -r))

cat >> "$TEMP_FILE" <<'EOF'
# Usage in main nginx config (server block):
#
# Include this file:
#   include /etc/nginx/conf.d/repo-codenames.conf;
#
# Then use $repo_pool_locations variable:
#   location ~ ^/pool/(.*)$ {
#       try_files $uri $repo_pool_locations =404;
#   }

EOF

# Generate variable with pool locations
echo "# Pool fallback paths (newest releases first)" >> "$TEMP_FILE"
echo "geo \$repo_pool_locations {" >> "$TEMP_FILE"
echo "    default \"" >> "$TEMP_FILE"

for cn in "${sorted_codenames[@]}"; do
    echo -n "/${cn}/\$uri " >> "$TEMP_FILE"
done

cat >> "$TEMP_FILE" <<'EOF'
";
}
EOF

echo -e "${GREEN}✓ Configuration generated${NC}"

# Install configuration
echo ""
echo -e "${YELLOW}→ Installing configuration...${NC}"

# Create backup if file exists
if [ -f "$OUTPUT_FILE" ]; then
    backup="${OUTPUT_FILE}.backup-$(date +%Y%m%d_%H%M%S)"
    if cp "$OUTPUT_FILE" "$backup" 2>/dev/null || sudo cp "$OUTPUT_FILE" "$backup" 2>/dev/null; then
        echo "  Backup: $backup"
    fi
fi

# Install new config
if cp "$TEMP_FILE" "$OUTPUT_FILE" 2>/dev/null; then
    echo -e "  ${GREEN}✓ Installed: $OUTPUT_FILE${NC}"
elif command -v sudo >/dev/null 2>&1 && sudo cp "$TEMP_FILE" "$OUTPUT_FILE" 2>/dev/null; then
    echo -e "  ${GREEN}✓ Installed: $OUTPUT_FILE (with sudo)${NC}"
else
    echo -e "${RED}✗ Failed to install: $OUTPUT_FILE${NC}"
    echo "Manual installation required:"
    echo "  sudo cp $TEMP_FILE $OUTPUT_FILE"
    rm -f "$TEMP_FILE"
    exit 1
fi

rm -f "$TEMP_FILE"

# Test nginx configuration
echo ""
echo -e "${YELLOW}→ Testing nginx configuration...${NC}"
if nginx -t 2>&1 | grep -q "successful"; then
    echo -e "${GREEN}✓ Nginx configuration valid${NC}"
else
    echo -e "${RED}✗ Nginx configuration test failed${NC}"
    echo "Please check: sudo nginx -t"
    exit 1
fi

# Show suggested nginx reload command
echo ""
echo -e "${GREEN}=== Configuration updated successfully ===${NC}"
echo ""
echo -e "${BLUE}Next step:${NC}"
echo "  Reload nginx to apply changes:"
echo "    sudo systemctl reload nginx"
echo ""
echo "Or update manually if using custom nginx config"

