You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.4 KiB

  1. #!/bin/bash
  2. set -eux
  3. NTFY_BROKER="${NTFY_BROKER:-core-01.0k.io}"
  4. ## Copy Ntfy key to root/.ssh/
  5. umask 077
  6. ntfy_key="src/etc/ssh/ntfy-key"
  7. if [ ! -f "$ntfy_key" ]; then
  8. echo "Error: ntfy key not found" >&2
  9. exit 1
  10. fi
  11. ntfy_key_dest=/etc/ssh/ntfy-key
  12. if [ ! -f "$ntfy_key_dest" ]; then
  13. cat "$ntfy_key" |
  14. gpg -d --batch --yes --passphrase 'uniquepass' > "$ntfy_key_dest" || {
  15. echo "Error while unpacking ntfy key to '${ntfy_key_dest}'" >&2
  16. exit 1
  17. }
  18. fi
  19. ## Request token to ntfy server and add to config file
  20. known_host="/root/.ssh/known_hosts"
  21. if ! ssh-keygen -F "$NTFY_BROKER" -f "$known_host" >/dev/null; then
  22. ssh-keyscan -H "$NTFY_BROKER" >> "$known_host" || {
  23. echo "Error while adding '$NTFY_BROKER' to known_hosts" >&2
  24. exit 1
  25. }
  26. fi
  27. config_file="/etc/ntfy/ntfy.conf"
  28. mkdir -p "${config_file%/*}"
  29. if ! [ -f "$config_file" ]; then
  30. touch "$config_file" || {
  31. echo "Error: couldn’t create config file $config_file" >&2;
  32. exit 1
  33. }
  34. fi
  35. LOGIN=""
  36. PASSWORD=""
  37. source "$config_file"
  38. ## Note that we reauire the forcing of stdin to /dev/null to avoid
  39. ## the rest of the script to be vacuumed by the ssh command.
  40. ## This effect will only happen when launching this script in special
  41. ## conditions involving stdin.
  42. cred=$(ssh -i "$ntfy_key_dest" ntfy@"${NTFY_BROKER}" \
  43. request-token "$LOGIN" "$PASSWORD" </dev/null) || {
  44. echo "Error while requesting token to ntfy server" >&2
  45. exit 1
  46. }
  47. ## XXXvlab: ideally it should be received from the last call
  48. server="https://ntfy.0k.io/"
  49. login=$(printf "%q" "${cred%$'\n'*}")
  50. password=$(printf "%q" "${cred#*$'\n'}")
  51. ## check if password doesn't contain '%'
  52. for var in server login password; do
  53. if [ -z "${!var}" ] || [[ "${!var}" == *$'\n'* ]]; then
  54. echo "Error: couldn't infer $var from ntfy server. Received:" >&2
  55. printf "%s" "$cred" | sed -r 's/^/ | /g' >&2
  56. exit 1
  57. fi
  58. if [[ "${!var}" == *%* ]]; then
  59. ## We need a separator char for sed replacement in the config file
  60. echo "Error: forbidden character '%' found in $var" >&2
  61. exit 1
  62. fi
  63. if grep -qE "^${var^^}=" "$config_file"; then
  64. sed -ri "s%^${var^^}=.*$%${var^^}=\"${!var}\"%g" "$config_file"
  65. else
  66. echo "${var^^}=\"${!var}\"" >> "$config_file"
  67. fi
  68. done
  69. if ! [ -f "/etc/ntfy/topics.yml" ]; then
  70. cat <<EOF > /etc/ntfy/topics.yml
  71. main:
  72. - \${LOGIN}_main
  73. EOF
  74. fi