#! /bin/sh
# Read and export debian specific configuration
# Only exported variables will be passed on to gitlab app
export $(cat /etc/gitlab/gitlab-debian.conf|xargs)

echo "Initializing database..."
if [ "$(su postgres -c 'psql gitlab_production -c \\d')" = \
"No relations found." ]; then
  su ${gitlab_user} -s /bin/sh -c 'bundle exec rake gitlab:setup \
  RAILS_ENV=production force=yes'
  su ${gitlab_user} -s /bin/sh -c 'bundle exec rake gitlab:shell:install \
  REDIS_URL=redis://localhost:6379 \
  SHELL_ROOT_PATH=/usr/share/gitlab-shell RAILS_ENV=production'
else
  echo "gitlab_production database is not empty, skipping gitlab setup"
fi

echo "Precompiling assets..."
su ${gitlab_user} -s /bin/sh -c 'bundle exec rake assets:precompile RAILS_ENV=production'

# Start gitlab
if [ -d "/run/systemd/system" ]; then
  systemctl start gitlab.target
else
  invoke-rc.d gitlab start
fi

# Workaround for #813770
if [ "${GITLAB_HTTPS}" = "true" ]; then
  gl_proto="https"
  sed -i "s/#port: 80/port: 443/" ${gitlab_home}/config/gitlab.yml
  sed -i "s/https: false/https: true/" ${gitlab_home}/config/gitlab.yml
else
  gl_proto="http"
fi

sed -i \
"s/gitlab_url: http*:\/\/.*/gitlab_url: ${gl_proto}:\/\/${GITLAB_HOST}/"\
 ${gitlab_shell_root}/config.yml

# Check gitlab is configured correctly
su ${gitlab_user} -s /bin/sh -c 'bundle exec rake gitlab:check RAILS_ENV=production'

