#!/bin/bash

echo "postgres starting..."

chown mastodon:mastodon /var/run/postgresql
chown -R mastodon:mastodon /etc/postgresql

echo "local all all peer" > /etc/postgresql/10/main/pg_hba.conf
echo "local all mastodon peer" >> /etc/postgresql/10/main/pg_hba.conf
echo "local all root peer" >> /etc/postgresql/10/main/pg_hba.conf
echo "host all all 127.0.0.0/8 trust" >> /etc/postgresql/10/main/pg_hba.conf

if [[ ! -d /state/db ]]; then
    mkdir -p /state/db/data
    rsync -a /var/lib/postgresql/10/main/ /state/db/data/
    cp -a /etc/postgresql/10/main/* /state/db/
    grep -v '^data_directory' /state/db/postgresql.conf |
        grep -v "^ssl" |
        grep -v "^stats_temp_directory" > /state/db/postgresql.new
    echo "data_directory = '/state/db/data'" >> /state/db/postgresql.new
    echo "stats_temp_directory = '/tmp'" >> /state/db/postgresql.new
    mv /state/db/postgresql.new /state/db/postgresql.conf
    chown -R mastodon:mastodon /state/db
    chmod go-rwx /state/db/data
fi

function shutdown()
{
    echo "Shutting down PostgreSQL"
    pkill postgres
}

trap shutdown HUP INT QUIT ABRT KILL ALRM TERM TSTP

exec \
    chpst -u mastodon:mastodon \
    /usr/lib/postgresql/10/bin/postmaster -D /state/db 2>&1