apiVersion: v1
kind: ConfigMap
metadata:
  name: "postgres-backup-hook-config-map"
  annotations:
    rollme: {{ randAlphaNum 5 | quote }}
data:
  entrypoint.sh: |-
    #!/bin/bash
    echo "Fetching password from config.php"

    # sed removes ' , => spaces and db* from the string
    DBUSER=$(cat /nc-config/config.php | grep "dbuser" | sed "s/dbuser\| \|'\|,\|=>//g")
    DBPASS=$(cat /nc-config/config.php | grep "dbpassword" | sed "s/dbpassword\| \|'\|,\|=>//g")
    DBNAME=$(cat /nc-config/config.php | grep "dbname" | sed "s/dbname\| \|'\|,\|=>//g")
    [ -n "$DBUSER" ] && [ -n "$DBPASS" ] && [ -n "$DBNAME" ] && echo "User, Database and password fetched from config.php"

    until pg_isready -U ${POSTGRES_USER} -h ${POSTGRES_HOST}; do sleep 2; done

    # pg_dump will automatically use the password from the PGPASSWORD environment variable
    echo "Creating backup of ${DBNAME} database as ${DBUSER}"
    PGPASSWORD=${DBPASS} pg_dump -U $DBUSER -d $DBNAME --host=${POSTGRES_HOST} > /postgres_backups/$BACKUP_NAME \
      && echo "Backup created successfully" \
      || echo "Backup failed"
