#!/usr/bin/bash

if [ $# -lt 2 ]; then
    echo "Usage: $0 [--dry] <problem> <file>"
    exit 1
fi

DRY_RUN="false"
while [[ $# -gt 0 ]]; do
    case $1 in
        --dry)
            DRY_RUN=true
            shift
            ;;
        *)
            if [ -z "$PROBLEM" ]; then
                PROBLEM="$1"
            elif [ -z "$FILE" ]; then
                FILE="$1"
            else
                echo "Error: Too many arguments."
                echo "Usage: $0 [--dry] <problem> <file>"
                exit 1
            fi
            shift
            ;;
    esac
done
if [ -z "$PROBLEM" ]; then
    echo "Error: Problem parameter is required."
    echo "Usage: $0 [--dry] <problem> <file>"
    exit 1
fi
if [ -z "$FILE" ]; then
    echo "Error: File parameter is required."
    echo "Usage: $0 [--dry] <problem> <file>"
    exit 1
fi

USERNAME=$(whoami)
CREDENTIALS_FILE="$HOME/.thuscc_credentials"
if [ ! -f "$CREDENTIALS_FILE" ]; then
    echo "Submit password for $USERNAME not set."
    read -sp "Enter your submit password: " PASSWORD
    echo "$PASSWORD" > "$CREDENTIALS_FILE"
    chmod 600 "$CREDENTIALS_FILE"
    echo "Password saved in '$CREDENTIALS_FILE'."
else
    PASSWORD=$(cat "$CREDENTIALS_FILE")
fi

if [ ! -f "$FILE" ]; then
    echo "Error: File '$FILE' does not exist."
    exit 1
fi
if ! file "$FILE" | grep -q "text"; then
    echo "Error: File '$FILE' is not a text file."
    exit 1
fi

SUBMIT_TIME=$(date +"%Y-%m-%d %H:%M:%S")

SERVER_URL="https://rank.thuscc24.thusaac.com/api/submit"

RESPONSE=$(/usr/bin/curl -s -X POST \
    -F "file=@$FILE" \
    -F "data={
        \"username\": \"$USERNAME\",
        \"password\": \"$PASSWORD\",
        \"problem\": \"$PROBLEM\",
        \"submitTime\": \"$SUBMIT_TIME\",
        \"dryRun\": \"$DRY_RUN\"
    }" "$SERVER_URL") 

MESSAGE=$(echo "$RESPONSE" | grep -oP '"message"\s*:\s*"\K[^"]+')

if [ -n "$MESSAGE" ]; then
    echo "Server Message: $MESSAGE"
    if [ "$MESSAGE" == "Wrong password." ]; then
        rm "$CREDENTIALS_FILE"
    fi
else
    echo "Error: Failed to parse server response."
    echo "Full response: $RESPONSE"
fi