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.

99 lines
2.3 KiB

  1. #!/bin/sh
  2. PSQL="/usr/bin/psql"
  3. free_megs() {
  4. fsdir=$1
  5. while [ ! -d "$fsdir" ]; do
  6. fsdir="$(dirname "$fsdir")"
  7. done
  8. df -m $fsdir | while read fs bl us av cap mnt; do [ "$av" = "Available" ] || echo $av; done
  9. }
  10. pg_init_data() {
  11. # make sure we got at least 50MB of free space
  12. [ $(free_megs "$1") -lt 50 ] && return 1
  13. pg_ctl initdb -U postgres -D "$1"
  14. }
  15. pg_server_ready() {
  16. t=0
  17. while [ $t -le 90 ]; do
  18. psql -h /var/run/postgresql/ -U postgres -c "\q" 1>/dev/null 2>/dev/null && return 0
  19. t=$((t+1))
  20. sleep 1
  21. done
  22. return 1
  23. }
  24. pg_test_db() {
  25. echo "SELECT datname FROM pg_catalog.pg_database WHERE datname = '$1';" |
  26. $PSQL -h /var/run/postgresql -w -U "postgres" -d "template1" -q |
  27. grep -q "0 rows" && return 1
  28. return 0
  29. }
  30. pg_include_sql() {
  31. if [ "$3" ]; then
  32. env PGPASSWORD="$3" $PSQL -h /var/run/postgresql -U "$2" -d "$1" -e -f "$4"
  33. return $?
  34. else
  35. $PSQL -w -h /var/run/postgresql -U "$2" -d "$1" -e -f "$4"
  36. return $?
  37. fi
  38. }
  39. # $1: dbname, $2: username, $3: password, $4: sql populate script
  40. pg_require_db() {
  41. local ret
  42. local dbname="$1"
  43. local dbuser="$2"
  44. local dbpass="$3"
  45. local exuser
  46. pg_test_db $@ && return 0
  47. shift ; shift ; shift
  48. echo "CREATE DATABASE $dbname;" |
  49. $PSQL -h /var/run/postgresql -U postgres -d template1 -e || return $?
  50. if [ "$dbuser" ]; then
  51. echo "SELECT usename FROM pg_catalog.pg_user WHERE usename = '$dbuser';" |
  52. $PSQL -h /var/run/postgresql -U postgres -d template1 -e | grep -q "0 rows" &&
  53. ( echo -n "CREATE USER $dbuser"
  54. [ "$dbpass" ] && echo -n " WITH PASSWORD '$dbpass'"
  55. echo " NOCREATEDB NOSUPERUSER NOCREATEROLE NOINHERIT;" ) |
  56. $PSQL -h /var/run/postgresql -U postgres -d template1 -e
  57. echo "GRANT ALL PRIVILEGES ON DATABASE \"$dbname\" TO $dbuser;" |
  58. $PSQL -h /var/run/postgresql -U postgres -d template1 -e
  59. fi
  60. while [ "$1" ]; do
  61. pg_include_sql "$dbname" "$dbuser" "$dbpass" "$1"
  62. ret=$?
  63. [ $ret != 0 ] && break
  64. shift
  65. done
  66. return $ret
  67. }
  68. uci_require_db() {
  69. local dbname dbuser dbpass dbscript
  70. config_get dbname $1 name
  71. config_get dbuser $1 user
  72. config_get dbpass $1 pass
  73. config_get dbscript $1 script
  74. pg_require_db "$dbname" "$dbuser" "$dbpass" $dbscript
  75. }
  76. [ "$1" = "init" ] && {
  77. . /lib/functions.sh
  78. pg_server_ready $2 || exit 1
  79. config_load postgresql
  80. config_foreach uci_require_db postgres-db
  81. }