contains_all_chars.sh 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/bin/bash
  2. # Bash script to be run as CGI and act as a
  3. # JSON api with a single method
  4. #
  5. # This is not the least bit practical but
  6. # I thought it would be a fun exercise
  7. #####################
  8. # HTTP functions
  9. #####################
  10. http_response() {
  11. echo "HTTP/1.1 $response_code"
  12. for h in "${headers[@]}"; do
  13. echo $h
  14. done
  15. echo -n -e "\n"
  16. }
  17. send_response() {
  18. http_response
  19. echo $body
  20. exit
  21. }
  22. #####################
  23. # API method(s)
  24. #####################
  25. contains_all_lowercase_chars_in_latin_alphabet() {
  26. input_string=$1
  27. wanted_chars='abcdefghijklmnopqrstuvwxyz'
  28. # count unique characters in $wanted_chars
  29. wanted_chars_c=$(echo $wanted_chars | grep -o . | sort | uniq | wc -l)
  30. # remove non-matching characters from input, and count unique remaining characters
  31. uniq_matching_chars_c=$(echo $input_string | tr -dc "$wanted_chars" | grep -o . | sort | uniq | wc -l )
  32. # if counts match, it contains all chars, return appropriate exit codes
  33. if [[ $uniq_matching_chars_c -eq $wanted_chars_c ]]; then
  34. return 0
  35. else
  36. return 1
  37. fi
  38. }
  39. #####################
  40. # Do the things
  41. #####################
  42. # variables needed for responses
  43. response_code="200 OK"
  44. headers=()
  45. body=''
  46. # this api endpoint requires you to post data
  47. if [[ $REQUEST_METHOD != "POST" ]]; then
  48. response_code="400 Bad Request"
  49. headers+=('Content-type: application/json')
  50. body='{"error": "Invalid http method", "result": null}'
  51. send_response
  52. fi
  53. # posted data is accessed from stdin
  54. read data
  55. contains_all_lowercase_chars_in_latin_alphabet "$data"
  56. if [[ $? -eq 0 ]]; then
  57. body='{"error": null, "result": true}'
  58. else
  59. body='{"error": null, "result": false}'
  60. fi
  61. response_code="200 OK"
  62. headers+=('Content-type: text/json')
  63. send_response