#!/bin/bash
# Bash script to be run as CGI and act as a
# JSON api with a single method
#
# This is not the least bit practical but
# I thought it would be a fun exercise


#####################
# HTTP functions
#####################
http_response() {
	echo "HTTP/1.1 $response_code"
	for h in "${headers[@]}"; do
		echo $h
	done
	echo -n -e "\n"
}

send_response() {
	http_response
	echo $body
	exit
}

#####################
# API method(s)
#####################
contains_all_lowercase_chars_in_latin_alphabet() {
	input_string=$1
	wanted_chars='abcdefghijklmnopqrstuvwxyz'

	# count unique characters in $wanted_chars
	wanted_chars_c=$(echo $wanted_chars | grep -o . | sort | uniq | wc -l)

	# remove non-matching characters from input, and count unique remaining characters
	uniq_matching_chars_c=$(echo $input_string | tr -dc "$wanted_chars" | grep -o . | sort | uniq | wc -l )

	# if counts match, it contains all chars, return appropriate exit codes
	if [[ $uniq_matching_chars_c -eq $wanted_chars_c ]]; then
        	return 0
	else
		return 1
	fi
}


#####################
# Do the things
#####################

# variables needed for responses
response_code="200 OK"
headers=()
body=''

# this api endpoint requires you to post data
if [[ $REQUEST_METHOD != "POST" ]]; then
	response_code="400 Bad Request"
	headers+=('Content-type: application/json')
	body='{"error": "Invalid http method", "result": null}'
	send_response
fi

# posted data is accessed from stdin
read data

contains_all_lowercase_chars_in_latin_alphabet "$data"
if [[ $? -eq 0 ]]; then
	body='{"error": null, "result": true}'
else
	body='{"error": null, "result": false}'
fi

response_code="200 OK"
headers+=('Content-type: text/json')
send_response

