#!/usr/bin/env bash
set -euo pipefail

# Determine target faspexctl file path
TARGET_FILE="${1:-}"

if [ -z "$TARGET_FILE" ]; then
    if [ -f "/opt/aspera/faspex/bin/faspexctl" ]; then
        TARGET_FILE="/opt/aspera/faspex/bin/faspexctl"
    elif [ -f "./faspexctl" ]; then
        TARGET_FILE="./faspexctl"
    else
        echo "Error: faspexctl file not found. Please provide path as argument." >&2
        echo "Usage: $0 [/path/to/faspexctl]" >&2
        exit 1
    fi
fi

if [ ! -f "$TARGET_FILE" ]; then
    echo "Error: Target file '$TARGET_FILE' does not exist." >&2
    exit 1
fi

# Check if patch is already present
if grep -q '/opt/aspera/faspex-router/nginx.conf' "$TARGET_FILE" && grep -q 'http2 off;' "$TARGET_FILE"; then
    echo "faspexctl at '$TARGET_FILE' is already patched."
    exit 0
fi

# Create backup with timestamp
BACKUP_FILE="${TARGET_FILE}.bak.$(date +%Y%m%d%H%M%S)"
cp -p "$TARGET_FILE" "$BACKUP_FILE"
echo "Created backup: $BACKUP_FILE"

TMP_FILE=$(mktemp)

# Inject the router configuration update into function start right after docker compose up
awk '
{
    print $0
}
/docker compose up --no-deps -d/ {
    print "    if [ \"$#\" -eq 0 ] || echo \"$@\" | grep -qE \"(faspex-)?router\"; then"
    print "        if is_container_running \"faspex-router\"; then"
    print "            docker exec faspex-router sed -i \"s/http2 on;/http2 off;/\" /opt/aspera/faspex-router/nginx.conf"
    print "            docker exec faspex-router nginx -s reload -c /opt/aspera/faspex-router/nginx.conf &>/dev/null || true"
    print "        fi"
    print "    fi"
}
' "$TARGET_FILE" > "$TMP_FILE"

# Preserve original permissions
chmod --reference="$TARGET_FILE" "$TMP_FILE" 2>/dev/null || chmod 755 "$TMP_FILE"
mv "$TMP_FILE" "$TARGET_FILE"

# Verify patch was applied
if grep -q 'http2 off;' "$TARGET_FILE"; then
    echo "Successfully patched '$TARGET_FILE'."
else
    echo "Error: Failed to apply patch to '$TARGET_FILE'. Restoring backup..." >&2
    cp -p "$BACKUP_FILE" "$TARGET_FILE"
    exit 1
fi