#!/bin/sh -e # # 2011 Steven Armstrong (steven-cdist at armstrong.cc) # 2020 Dennis Camera (dennis.camera at ssrq-sds-fds.ch) # # This file is part of cdist. # # cdist is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # cdist is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with cdist. If not, see . # quote() { if test $# -gt 0 then printf '%s' "$*" else cat - fi | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/'/" } case $(cat "${__global:?}/explorer/os") in (netbsd) postgres_user='pgsql' ;; (openbsd) postgres_user='_postgresql' ;; (*) postgres_user='postgres' ;; esac rolename=${__object_id:?} state_is=$(cat "${__object:?}/explorer/state") state_should=$(cat "${__object:?}/parameter/state") if test "${state_is}" = "${state_should}" then exit 0 fi if test -s "${__object:?}/parameter/password" then quoted_password=$( delim='$$' # NOTE: Strip away trailing $ because with it the check breaks # if the password ends with $ + random value. while grep -q -F "${delim%$}" "${__object:?}/parameter/password" do delim="\$$(LC_ALL=C tr -cd '[:alpha:]' /dev/null)$" done psql_query() { printf 'su -l %s -c %s\n' \ "$(quote "${postgres_user}")" \ "$(quote "psql postgres -wc $(quote "$1")")" } raw_passwd=$(cat "${__object:?}/parameter/password"; printf .) # shellcheck disable=SC2016 printf '%s%s%s' "${delim}" "${raw_passwd%?.}" "${delim}" ) fi role_properties_should() { _props= for _prop in login createdb createrole superuser do _props="${_props}${_props:+ }$( if test -f "${__object:?}/parameter/${_prop}" then echo "${_prop}" else echo "no${_prop}" fi \ | tr '[:lower:]' '[:upper:]')" done printf '%s\n' "${_props}" unset _prop _props } case ${state_should} in (present) case ${state_is} in (absent) psql_query "$(printf 'CREATE ROLE "%s" WITH %s PASSWORD %s;' \ "${rolename}" "$(role_properties_should)" "${quoted_password:-NULL}")" ;; (different*) if expr "${state_is}" : 'different.*properties' >/dev/null then psql_query "ALTER ROLE \"${rolename}\" WITH $(role_properties_should);" fi if expr "${state_is}" : 'different.*password' >/dev/null then psql_query "ALTER ROLE \"${rolename}\" WITH PASSWORD ${quoted_password:-NULL};" fi ;; (*) printf 'Invalid state reported by state explorer: %s\n' "${state_is}" >&2 exit 1 ;; esac ;; (absent) printf 'su -l %s -c %s\n' \ "$(quote "${postgres_user}")" \ "$(quote "dropuser $(quote "${rolename}")")" ;; esac