#!/bin/sh

#################parse args####################
# Initialize variables to hold the parsed options
TASK_ID=""
TASK_TYPE=""

# Function to show the script usage
show_usage() {
    echo "hw2.sh -p TASK_ID -t TASK_TYPE [-h]" >&2
    echo >&2
    echo "Available Options:" >&2
    echo >&2
    echo "-p: Task id" >&2
    echo "-t JOIN_NYCU_CSIT|MATH_SOLVER|CRACK_PASSWORD: Task type" >&2
    echo "-h: Show the script usage" >&2
}


# function of cracking password
crack() {
    UPPER="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    LOWER="abcdefghijklmnopqrstuvwxyz"
    orig="A-Za-z"
    str="$1"
    shmnt=0
    found=0
    while [ $shmnt -lt 26 ]
    do
        sub=$(awk -v up="$UPPER" -v lo="$LOWER" -v sp="$shmnt" 'BEGIN { 
            sub1 = substr(up, sp+1, 26-sp)
            sub2 = substr(up, 1, sp)
            sub3 = substr(lo, sp+1, 26-sp)
            sub4 = substr(lo, 1, sp)
            print sub1 sub2 sub3 sub4
            }')
        resultt=$(echo "$str" | tr "[$orig]" "[$sub]")
        shmnt=$((shmnt+1))
        if echo "$resultt" | grep -q "NYCUNASA"; then
            ans="$resultt"
            found=1
            break
        fi
    done
    if [ $found -eq 0 ]; then
        ans="Invalid problem"
    fi
echo "$ans"
}

get_task(){
    #curl -X POST -H "Content-Type: application/json" -d '{"id": "4a9c99f4-0241-4f3d-a003-7b2f6bb455db","type": "CRACK_PASSWORD","status": "PENDING","problem": "ALPHANFN{QfLWrLExdqgSufIi}"}' "https://echo.free.beeceptor.com" -o test
    #curl -X POST -H "Content-Type: application/json" -d '{"id": "4a9c99f4-0241-4f3d-a003-7b2f6bb455db","type": "MATH_SOLVER","status": "PENDING","problem": "1 + 4 = ?"}' "https://echo.free.beeceptor.com" -o test
    curl  -s "http://10.113.0.253/tasks/$TASK_ID" -o "./lab2_test/$TASK_ID"
    TASK=$(jq -r '.type' "./lab2_test/$TASK_ID")
    PROBLEM=$(jq -r '.problem' "./lab2_test/$TASK_ID" )
    #STATUS=$(jq -r '.status' "./lab2_test/$TASK_ID")
    cat "./lab2_test/$TASK_ID"
    echo
    #rm "./lab2_test/$TASK_ID"
}

submit(){
    #curl -X POST -H "Content-Type: application/json" -d "{\"answer\":  \"""$1""\"}" "https://echo.free.beeceptor.com" -o test1
    echo "ANSWER   :    $1"
    curl -s -X POST -H "Content-Type: application/json" -d "{\"answer\":  \"""$1""\"}" "http://10.113.0.253/tasks/$TASK_ID/submit" -o "./lab2_ans/$TASK_ID"
    jq -r '{result:    .message}' "./lab2_ans/$TASK_ID"
}


if [ $# -eq 0 ]; then
    show_usage
    exit 1
fi

# Parse options using a while loop
while getopts ":p:t:h" opt; do
    case "$opt" in
        p) 
            TASK_ID="$OPTARG"
            ;;
        t) 
            TASK_TYPE="$OPTARG"
            ;;
        h) 
            show_usage
            exit 0
            ;;
        ?) 
            # Invalid option
            show_usage
            exit 1
            ;;
    esac
done

# Ensure that both -p and -t are provided
if [ -z "$TASK_ID" ] || [ -z "$TASK_TYPE" ]; then
    #echo "Error: Both -p (Task ID) and -t (Task Type) are required."
    show_usage
    exit 1
fi

# Validate the task type
case "$TASK_TYPE" in
    JOIN_NYCU_CSIT|MATH_SOLVER|CRACK_PASSWORD)
        # Task type is valid
        ;;
    *)
        echo "Invalid task type" >&2
        #show_usage
        exit 1
        ;;
esac

# Display the parsed options
echo "Task ID: $TASK_ID"
echo "Task Type: $TASK_TYPE"

#############start#################

echo "#######################   start   ##############################"
echo "$TASK_ID"
echo "$TASK_TYPE"
echo "$TASK"
echo "#######################  end    ################################"

get_task
if [ "$TASK_TYPE" != "$TASK" ];then
    echo "Task type not match" >&2
    exit 1
fi

case "$TASK" in
    "CRACK_PASSWORD")
        result=$(crack "$PROBLEM")
    ;;
    "JOIN_NYCU_CSIT")
        echo "$PROBLEM" >> ./links
        result="I Love NYCU CSIT"
    ;;
    "MATH_SOLVER")
        cleaned=$(echo "$PROBLEM" | sed 's/=.*//')
        IFS=" "
        read -r i1 op i2 <<EOF
$cleaned
EOF
        if [ "$op" = '+' ]
        then
            result=$((i1+i2))
        elif [ "$op" = '-' ]
  	then
            result=$((i1-i2))
	else
	    result="Invalid problem"
        fi
    echo "$result"
    ;;
esac

submit "$result"


