fork 0k-charms
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.3 KiB

  1. #!/bin/bash
  2. ## When writing relation script, remember:
  3. ## - they should be idempotents
  4. ## - they can be launched while the dockers is already up
  5. ## - they are launched from the host
  6. ## - the target of the link is launched first, and get a chance to ``relation-set``
  7. ## - both side of the scripts get to use ``relation-get``.
  8. DBNAME=$(relation-get dbname) || {
  9. DBNAME="$BASE_SERVICE_NAME"
  10. relation-set dbname "$DBNAME"
  11. }
  12. USER=$(relation-get user) || {
  13. USER="$BASE_SERVICE_NAME"
  14. relation-set user "$USER"
  15. }
  16. . lib/common
  17. set -e
  18. ## YYY: check that password was not already generated/set for the same user
  19. ## use session state storage.
  20. ## is there a previous password set for user $USER ?
  21. NO_PREVIOUS_PASS=
  22. PREVIOUS_PASSWORD_PATH="$state_tmpdir/$SERVICE_NAME/pwd/$USER"
  23. PREVIOUS_PASSWORD=$(cat "$PREVIOUS_PASSWORD_PATH" 2>/dev/null) || NO_PREVIOUS_PASS=true
  24. if PASSWORD="$(relation-get password 2>/dev/null)"; then
  25. if [ -z "$NO_PREVIOUS_PASS" -a "$PREVIOUS_PASSWORD" != "$PASSWORD" ]; then
  26. die "Inconsistent password specification for user '$USER' on ${DARKYELLOW}$TARGET_SERVICE_NAME$NORMAL."
  27. fi
  28. else
  29. if [ "$PREVIOUS_PASSWORD" ]; then
  30. PASSWORD="${PREVIOUS_PASSWORD}"
  31. else
  32. PASSWORD="$(gen_password)"
  33. info "Generated a new password for use '$USER'."
  34. fi
  35. fi
  36. POSTGIS=$(relation-get postgis 2>/dev/null) || true
  37. UNACCENT=$(relation-get unaccent 2>/dev/null) || true
  38. ensure_db_docker_running
  39. ## XXXvlab: should send all these into only one docker...
  40. db_has_database "$DBNAME" || UNACCENT="$UNACCENT" POSTGIS="$POSTGIS" db_create "$DBNAME"
  41. if ! db_has_user "$USER"; then
  42. info "Creating a new user $USER."
  43. db_create_user "$USER" "$PASSWORD"
  44. else
  45. info "Updating password of user $USER."
  46. db_change_password "$USER" "$PASSWORD"
  47. fi
  48. db_grant_rights "$DBNAME" "$USER"
  49. info "Granted rights on database '$DBNAME' to user '$USER'."
  50. ##
  51. ## PGPASS
  52. ##
  53. pgpass_line="*:*:*:$USER:$PASSWORD"
  54. pgpass_file="$CONFIGSTORE/$BASE_SERVICE_NAME/root/.pgpass"
  55. if [ -e "$pgpass_file" ]; then
  56. sed -ri "/^.+:.+:.+:$USER:.*$/d" "$pgpass_file"
  57. fi
  58. mkdir -p "$(dirname "$pgpass_file")"
  59. echo "$pgpass_line" >> "$pgpass_file"
  60. chmod 600 "$pgpass_file"
  61. ##
  62. ## Saving password
  63. ##
  64. relation-set password "$PASSWORD"
  65. mkdir -p "$(dirname "$PREVIOUS_PASSWORD_PATH")"
  66. echo "$PASSWORD" > "$PREVIOUS_PASSWORD_PATH"