#!/bin/bash
QUERY_STRING=$(echo "${QUERY_STRING}" | sed 's/;//g')
function urldecode() { : "${*//+/ }"; echo -e "${_//%/\\x}"; }

if [ "${QUERY_STRING}" ]; then
    export IFS="&"
    for cmd in ${QUERY_STRING}; do
        if [ "$(echo $cmd | grep '=')" ]; then
            key=$(echo $cmd | awk -F '=' '{print $1}')
            value=$(echo $cmd | awk -F '=' '{print $2}')
            eval $key=$value
        fi
    done
fi

# Extract phone number and message from inputs
phone_number="$number"
message="$msg"

# Prepare AT command with phone number and message
ATCMD="AT+CMGS=\"$phone_number\""

MYATCMD=$(printf '%b\n' "${ATCMD//%/\\x}")
if [ -n "${MYATCMD}" ]; then
    x=$(urldecode "$ATCMD")
    # Send the AT command to initiate message sending
    echo -en "$x\r\n" | microcom /dev/ttyOUT2
    # Wait for a brief moment (assuming the message sending is instantaneous)
    sleep 1
fi

# Send the message
echo -en "$message\c"

# Send Ctrl+Z to terminate the message
echo -en "\032"

# Ensure microcom reads the response (assuming microcom will show response instantly)
sleep 1

# Capture and output the response
runcmd=$(microcom /dev/ttyOUT2)
echo "Content-type: text/plain"
echo "$runcmd"