#!/bin/bash

# Read system name from configuration file
# Returns the system name if configured, otherwise returns an empty string
get_system_name() {
    local sysname_file="/usr/panaetc/sysname.conf"

    # Check if configuration file exists and is readable
    if [ ! -f "$sysname_file" ] || [ ! -r "$sysname_file" ]; then
        echo ""
        return
    fi

    # Source the configuration file in a subshell to avoid polluting environment
    local sysname
    sysname=$(
        unset SYSNAME
        # shellcheck disable=SC1090
        . "$sysname_file" 2>/dev/null
        echo "${SYSNAME}"
    )

    # Sanitize system name to prevent HTML injection
    # Remove HTML and sed-sensitive characters
    if [ -n "$sysname" ]; then
        # Remove HTML and sed-sensitive characters for security
        sysname=$(echo "$sysname" | sed "s/[<>\"&'|\\\\]//g")
    fi

    # Return system name if not empty after sanitization, otherwise return default
    if [ -n "$sysname" ]; then
        echo "$sysname"
    else
        echo ""
    fi
}

# Get system name for page title
SYSTEM_NAME=$(get_system_name)

# Output HTTP headers
printf "Content-type: text/html; charset=GB2312\r\n"
printf "Cache-Control: no-cache\r\n"
printf "\r\n"

# Output HTML with dynamic title replacement
# Replace <title> tag when system name is configured, otherwise keep original title
if [ -n "$SYSTEM_NAME" ]; then
    # Use flexible pattern to match any title content and prepend system name
    # This avoids dependency on specific title text
    sed -e "s|<title>\([^<]*\)</title>|<title>[${SYSTEM_NAME}] \1</title>|" \
        /usr/ramdisk/admin/html/App/unisase-agent/agent_main.html
else
    cat /usr/ramdisk/admin/html/App/unisase-agent/agent_main.html
fi
