#!/bin/sh -e
# Migrate the GitLab database after an upgrade (gitlab-migrate.service):
# dump the database (GITLAB_BACKUP_BEFORE_MIGRATE=yes in /etc/sysconfig/gitlab),
# run the migrations and store the migrated version to /var/lib/gitlab/VERSION.
# The upgrade check of the package (%pre) takes the version from there.

umask 077
export TMPDIR=/var/lib/gitlab/tmp TMP=/var/lib/gitlab/tmp
export RAILS_ENV="${RAILS_ENV:-production}" EXECJS_RUNTIME=Disabled
GITLAB_BACKUP_BEFORE_MIGRATE="${GITLAB_BACKUP_BEFORE_MIGRATE:-yes}"

GITLAB_DIR=/usr/share/gitlab
STATE_DIR=/var/lib/gitlab
BACKUP_DIR=$STATE_DIR/backups
VERSION="$(cat $GITLAB_DIR/VERSION)"
STAMP=$STATE_DIR/VERSION

if [ "$(cat $STAMP 2>/dev/null)" = "$VERSION" ] ; then
	echo "The database is migrated to GitLab $VERSION already"
	exit 0
fi

if [ ! -s /etc/gitlab/database.yml ] ; then
	echo "/etc/gitlab/database.yml is missing: configure the database first" >&2
	exit 1
fi

dbenv=$(/usr/lib/gitlab/gitlab-db-env)
eval "$dbenv"

if [ "$(psql -X -At -c "SELECT to_regclass('schema_migrations') IS NOT NULL")" != "t" ] ; then
	echo "The database $PGDATABASE is not initialized." >&2
	echo "Initialize an existing empty database owned by git (no CREATEDB needed):" >&2
	echo "  systemctl enable --now gitaly" >&2
	echo "  gitlab-setup" >&2
	echo "  systemctl enable --now gitlab.target gitlab-workhorse" >&2
	exit 1
fi

cd "$GITLAB_DIR"
status=$(mktemp "$TMPDIR/migrate-status.XXXXXX")
trap 'rm -f "$status"' EXIT HUP INT TERM
/usr/bin/bundle exec rake db:migrate:status > "$status"
if ! grep -q '^[[:space:]]*down[[:space:]]' "$status" ; then
	echo "No pending database migrations for GitLab $VERSION"
	echo "$VERSION" > "$STAMP.new"
	mv -f "$STAMP.new" "$STAMP"
	exit 0
fi

if [ "$GITLAB_BACKUP_BEFORE_MIGRATE" = "yes" ] ; then
	dump="$BACKUP_DIR/db-before-$VERSION-$(date +%Y%m%d%H%M%S).dump"
	echo "Dumping the database $PGDATABASE to $dump ..."
	mkdir -p "$BACKUP_DIR"
	chmod 0700 "$BACKUP_DIR"
	pg_dump -Fc -f "$dump.part"
	mv "$dump.part" "$dump"
fi

echo "Migrating the database $PGDATABASE to GitLab $VERSION ..."
cd $GITLAB_DIR
/usr/bin/bundle exec rake db:migrate

echo "$VERSION" > $STAMP.new
mv -f $STAMP.new $STAMP
echo "The database is migrated to GitLab $VERSION"
