#!/bin/bash

touch /state/.starting
echo "mastodon-startup starting up..."

if [[ ! -d /state/envdir ]]; then
    mkdir -p /state/envdir
fi

if [[ ! -e /state/envdir/HOME ]]; then
    echo "/mastodon" > /state/envdir/HOME
fi

if [[ ! -e /state/envdir/RAILS_ENV ]]; then
    echo "production" > /state/envdir/RAILS_ENV
fi

chown mastodon:mastodon /state/envdir /state/envdir/*

cd /mastodon/app

if [[ ! -e /state/envdir/OTP_SECRET ]]; then
  envdir /state/envdir \
      chpst -u mastodon:mastodon \
      bash -i -c "bundle exec rake secret > /state/envdir/OTP_SECRET"
fi

if [[ ! -e /state/envdir/SECRET_KEY_BASE ]]; then
  envdir /state/envdir \
      chpst -u mastodon:mastodon \
      bash -i -c "bundle exec rake secret > /state/envdir/SECRET_KEY_BASE"
fi

echo "
    create database mastodon_production;
    create user mastodon createdb;
    grant all privileges on database mastodon_production to mastodon;
" | chpst -u postgres:postgres psql

if [[ -n "$RUN_DB_MIGRATIONS" ]]; then
  echo "Running database migrations..."
  envdir /state/envdir \
      chpst -u mastodon:mastodon \
      bash -i -c "bundle exec rake db:migrate"
fi

rm /state/.starting
while true ; do
    sleep 86400
done