#! /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)

if ! [ -f "${gitlab_app_root}/config/secrets.yml" ]; then
  echo "Creating secrets.yml..."
  cd ${gitlab_app_root}
  su gitlab -c 'bundle exec rake config/initializers/secret_token.rb'
fi

# Check if the db is already present
if [ "$(LANG=C su postgres -c "psql gitlab_production -c \"\d\"")" = \
"No relations found." ]; then
  echo "Initializing database..."
  su ${gitlab_user} -s /bin/sh -c 'bundle exec rake db:schema:load'
  su ${gitlab_user} -s /bin/sh -c 'bundle exec rake db:seed_fu'
else
  echo "gitlab_production database is not empty, skipping gitlab setup"
  su ${gitlab_user} -s /bin/sh -c 'bundle exec rake db:migrate'
fi

# Restrict permissions for secret files
chmod 0700 ${gitlab_data_dir}/.gitlab_shell_secret

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

# Start gitlab
printf "Starting GitLab...\n"
service gitlab start

# Check gitlab is configured correctly
printf "Check if Gitlab is configured correctly...\n"
su ${gitlab_user} -s /bin/sh -c 'bundle exec rake gitlab:check RAILS_ENV=production'

