keyhelp_api.sh 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env sh
  2. keyhelp_api_deploy() {
  3. _cdomain="$1"
  4. _ckey="$2"
  5. _ccert="$3"
  6. _cca="$4"
  7. _debug _cdomain "$_cdomain"
  8. _debug _ckey "$_ckey"
  9. _debug _ccert "$_ccert"
  10. _debug _cca "$_cca"
  11. # Read config from saved values or env
  12. _getdeployconf DEPLOY_KEYHELP_HOST
  13. _getdeployconf DEPLOY_KEYHELP_API_KEY
  14. _debug DEPLOY_KEYHELP_HOST "$DEPLOY_KEYHELP_HOST"
  15. _secure_debug DEPLOY_KEYHELP_API_KEY "$DEPLOY_KEYHELP_API_KEY"
  16. if [ -z "$DEPLOY_KEYHELP_HOST" ]; then
  17. _err "KeyHelp host not found, please define DEPLOY_KEYHELP_HOST."
  18. return 1
  19. fi
  20. if [ -z "$DEPLOY_KEYHELP_API_KEY" ]; then
  21. _err "KeyHelp api key not found, please define DEPLOY_KEYHELP_API_KEY."
  22. return 1
  23. fi
  24. # Save current values
  25. _savedeployconf DEPLOY_KEYHELP_HOST "$DEPLOY_KEYHELP_HOST"
  26. _savedeployconf DEPLOY_KEYHELP_API_KEY "$DEPLOY_KEYHELP_API_KEY"
  27. _request_key="$(tr '\n' ':' <"$_ckey" | sed 's/:/\\n/g')"
  28. _request_cert="$(tr '\n' ':' <"$_ccert" | sed 's/:/\\n/g')"
  29. _request_ca="$(tr '\n' ':' <"$_cca" | sed 's/:/\\n/g')"
  30. _request_body="{
  31. \"name\": \"$_cdomain\",
  32. \"components\": {
  33. \"private_key\": \"$_request_key\",
  34. \"certificate\": \"$_request_cert\",
  35. \"ca_certificate\": \"$_request_ca\"
  36. }
  37. }"
  38. _hosts="$(echo "$DEPLOY_KEYHELP_HOST" | tr "," " ")"
  39. _keys="$(echo "$DEPLOY_KEYHELP_API_KEY" | tr "," " ")"
  40. _i=1
  41. for _host in $_hosts; do
  42. _key="$(_getfield "$_keys" "$_i" " ")"
  43. _i="$(_math "$_i" + 1)"
  44. export _H1="X-API-Key: $_key"
  45. _put_url="$_host/api/v2/certificates/name/$_cdomain"
  46. if _post "$_request_body" "$_put_url" "" "PUT" "application/json" >/dev/null; then
  47. _code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  48. else
  49. _err "Cannot make PUT request to $_put_url"
  50. return 1
  51. fi
  52. if [ "$_code" = "404" ]; then
  53. _info "$_cdomain not found, creating new entry at $_host"
  54. _post_url="$_host/api/v2/certificates"
  55. if _post "$_request_body" "$_post_url" "" "POST" "application/json" >/dev/null; then
  56. _code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  57. else
  58. _err "Cannot make POST request to $_post_url"
  59. return 1
  60. fi
  61. fi
  62. if _startswith "$_code" "2"; then
  63. _info "$_cdomain set at $_host"
  64. else
  65. _err "HTTP status code is $_code"
  66. return 1
  67. fi
  68. done
  69. return 0
  70. }