#!/bin/bash

set -e

RAVEN_TMP="${AUTOPKGTEST_TMP:-/tmp}/raven_test"
INPUT_PAYLOAD='input-payload.txt'
REMOTE_PAYLOAD='127.0.0.1/input-payload.txt'
PORT=8080

mkdir -p "$RAVEN_TMP"
cp debian/tests/source-data/"$INPUT_PAYLOAD" "${RAVEN_TMP}/"
cd "$RAVEN_TMP"

# Start Raven and perform upload
raven 127.0.0.1 "$PORT" --upload-dir "$RAVEN_TMP" --organize-uploads & sleep 5

if pgrep -x "raven" >/dev/null; then
    echo "Raven started successfully."
else
    echo "Raven failed to start or exited unexpectedly."
    exit 1
fi

# Upload the payload using curl
curl_output=$(curl -sS -X POST -F "file=@${RAVEN_TMP}/input-payload.txt" -F "submit=Upload" 127.0.0.1:"$PORT")

if [[ $? -ne 0 ]]; then
    echo "Failed to upload file using curl."
    exit 1
fi

# Normalize line endings
dos2unix -q "$REMOTE_PAYLOAD"

# Compare the original payload with the remote payload
diff "$INPUT_PAYLOAD" "$REMOTE_PAYLOAD" >/dev/null
if [[ $? -eq 0 ]]; then
    echo "Upload successful. Files match."
    # Clean up temporary directory
    rm -rf "${RAVEN_TMP}"
    exit 0
else
    echo "Upload failed or files differ."
    # Clean up temporary directory
    rm -rf "${RAVEN_TMP}"
    exit 1
fi

