#!/usr/bin/env bash

# Configuration
HOST="http://127.0.0.1"
API_KEY="<replace with your API key>"
CONVERSATION_ID=""

# Function to print usage banner
print_usage() {
    cat << EOF
Usage: $0 <file_path>

This script processes a file line by line and sends each line to a RAGFlow chat agent.

Arguments:
    <file_path>    Path to the file to be processed

Example:
    $0 /path/to/your/file.txt

Note: Make sure to set the correct HOST and API_KEY in the script before running.
EOF
}

# Check if a file path is provided
if [ $# -eq 0 ]; then
    print_usage
    exit 1
fi

FILE_PATH="$1"

# Check if the file exists and is readable
if [ ! -f "$FILE_PATH" ] || [ ! -r "$FILE_PATH" ]; then
    echo "Error: File does not exist or is not readable: $FILE_PATH"
    print_usage
    exit 1
fi

# Function to create a new conversation
create_conversation() {
    local response=$(curl -s -X GET "${HOST}/v1/api/new_conversation" \
         -H "Authorization: Bearer ${API_KEY}" \
         -H "Content-Type: application/json" \
         -d '{"user_id": "pentest_hero"}')
    
    echo $response | jq -r '.data.id'
}

# Function to send a message to the chat agent
send_message() {
    local message="$1"
    local escaped_message=$(echo "$message" | jq -sR .)
    local response=$(curl -s -X POST "${HOST}/v1/api/completion" \
         -H "Authorization: Bearer ${API_KEY}" \
         -H "Content-Type: application/json" \
         -d '{
               "conversation_id": "'"${CONVERSATION_ID}"'",
               "messages": [{"role": "user", "content": '"${escaped_message}"'}],
               "stream": false
             }')
    
    if echo "$response" | jq -e '.retcode == 102' > /dev/null; then
        echo "Error: Conversation not found. Creating new conversation."
        CONVERSATION_ID=$(create_conversation)
        send_message "$message"  # Retry with new conversation ID
    else
        #echo "Raw response: $response"
        echo $response | jq -r '.data.answer // "No answer found"'
    fi
}

# Create initial conversation
CONVERSATION_ID=$(create_conversation)
#echo "Created conversation with ID: $CONVERSATION_ID"

# Read the file line by line and send each line to the chat agent
while IFS= read -r line; do
    if [[ ! $line =~ "Ports:" ]]; then
        continue
    fi
    ip_address=$(echo "$line" | awk '{print $2}')
    hostname=$(echo "$line" | awk '{print $3}' | sed 's/[()]//g')
    printf -v separator '%*s' $(tput cols) '' && echo "${separator// /-}"
    echo "IP address: $ip_address   Hostname: $hostname"
    echo ""
    send_message "$line"
    
    sleep 1  # Add a small delay to avoid overwhelming the API
done < "$FILE_PATH"

echo "Finished processing file"