#!/bin/bash

# Configuration
NEXUS_URL="https://nexus.ellisbs.co.uk"
USERNAME="admin"
PASSWORD="$NEXUS_ADMIN"
PACKAGE_LIST_FILE="$1"

# --- DO NOT CHANGE ANYTHING BELOW THIS LINE ---

# Check for input file
if [ -z "$PACKAGE_LIST_FILE" ]; then
    echo "Usage: $0 <path_to_package_list_file>"
    exit 1
fi

# Check if file exists
if [ ! -f "$PACKAGE_LIST_FILE" ]; then
    echo "Error: File not found - $PACKAGE_LIST_FILE"
    exit 1
fi

# Function to check if a routing rule with a given name already exists
rule_exists() {
  local rule_name="$1"
  local http_code
  http_code=$(curl -s -o /dev/null -w "%{http_code}" -u "$USERNAME:$PASSWORD" "$NEXUS_URL/service/rest/v1/routing-rules/name/$rule_name")
  
  if [[ "$http_code" -eq 200 ]]; then
    return 0 # Rule exists
  else
    return 1 # Rule does not exist
  fi
}

echo "Starting to create Nexus routing rules from file: $PACKAGE_LIST_FILE"
echo "Target Nexus instance: $NEXUS_URL"
echo "--------------------------------------------------------"

# Read package list line by line
while IFS= read -r line; do
    # Trim whitespace and handle empty lines
    package_entry=$(echo "$line" | xargs)
    if [ -z "$package_entry" ]; then
        continue
    fi
    
    # Extract package name and version
    package_name=$(echo "$package_entry" | awk -F'@' '{print $1}')
    package_version=$(echo "$package_entry" | awk -F'@' '{print $2}')

    if [ -z "$package_version" ]; then
        echo "Skipping entry '$package_entry' as it does not contain a version."
        continue
    fi

    # Create a valid rule name
    rule_name="npm-block-${package_name}-${package_version}"
    
    echo "Processing package: $package_name (Rule Name: $rule_name)"

    # Check if the rule already exists
    if rule_exists "$rule_name"; then
      echo "  ➡️  Rule already exists. Skipping."
      continue
    fi
    
    # Create JSON payload with the correct format
    payload=$(jq -n \
      --arg rule_name "$rule_name" \
      --arg package_name "$package_name" \
      --arg package_version "$package_version" \
      '{
        "name": $rule_name,
        "description": "Blocks supplier chain security incident for \($package_name)@\($package_version)",
        "mode": "BLOCK",
        "matchers": [
          {
            "repositoryNames": ["npm-group"],
            "formats": ["npm"],
            "repositoryPathRegex": "/\($package_name)/-/\($package_name)-\($package_version).tgz"
          }
        ]
      }')

    echo "  ➡️  Generated payload:"
    echo "$payload" | jq . | sed 's/^/    /' # Re-format with jq for readability
    echo "  ➡️  Creating rule..."

    # Use a single curl command with separate output for http code and body
    response_out=$(mktemp)
    http_code=$(curl -s -X POST -H "Content-Type: application/json" \
                   -u "$USERNAME:$PASSWORD" --data-binary "$payload" \
                   -o "$response_out" \
                   -w "%{http_code}" \
                   "$NEXUS_URL/service/rest/v1/routing-rules")

    body=$(cat "$response_out")
    rm "$response_out"

    if [[ "$http_code" -ge 200 && "$http_code" -lt 300 ]]; then
        echo "  ✅ Success: Rule created for $package_name."
    else
        echo "  ❌ Error: Failed to create rule for $package_name."
        echo "  HTTP Code: $http_code"
        echo "  Response: $body"
    fi
    
    echo "--------------------------------------------------------"
done < "$PACKAGE_LIST_FILE"

echo "Script finished."
