#!/bin/sh

usage="$0 html_file.html"

if [ "$#" -ne 1 ]
then
    echo "$usage"
    exit 1
fi

html_file="$1"
if ! [ -f "$html_file" ]
then
    echo "error: '$html_file' is not a regular file."
    echo "$usage"
    exit 1
fi

# the weird << syntax: heredoc for multiline strings

awk_prog=$(cat  << 'EOF'

BEGIN {
  username = 0
  out_html = ""
  status_html="<div id="statuscafe"><div id="statuscafe-username">::USERNAME::</div><div id="statuscafe-content">::CONTENT::</div></div>"
}

/<!--[[:space:]]*status-cafe:[[:space:]]*[^[:space:]]+[[:space:]]*-->/ {
    sub(/<!--[[:space:]]*status-cafe:/, "<!-- status-cafe: ")
    in_uname = 0
    for (i = 1; i < NF; ++i) {
        if (in_uname) {

            username = $i;
            #print "username is " $i;
            break;
        }
        if ($i ~ /status-cafe:/) {
            in_uname = 1;
        }
    }

    if (get_username) {
        exit 0
    }
}

{
    out_html = out_html $0 "\n"
}

END {
    if (get_username) {
        print username
    } else {
        print out_html
    }
}

EOF
)

awk_json_parse=$(cat << 'EOF'

BEGIN {
    print("hello lmao");
}

{
    print $0
}

EOF
)

user_name="$(awk -v get_username=1 "$awk_prog" "$html_file")"
user_status_url="https://status.cafe/users/${user_name}/status.json"
echo "status url is '$user_status_url'"
echo "fetching status for user '$user_name'..."
result_json="$(curl -s "$user_status_url")"
#result_json='{"author":"fruit","content":"rain and thunder and sunshine","face":"🌈","timeAgo":"5 days ago"}'

echo "fetched json: $result_json"

echo "$result_json" | awk "$awk_json_parse"

