#! /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..."
  # Check if .secret file exist already in gitlab_app_root
  # See if it is an empty file
  test -e ${gitlab_app_root}/.secret &&\
  gitlab_app_secret=$(cat ${gitlab_app_root}/.secret);\
  test -n "${gitlab_app_secret}" ||\
  { gitlab_app_secret=$(openssl rand -hex 64)

  cp ${gitlab_app_root}/config/secrets.yml.example ${gitlab_app_root}/config/secrets.yml
  sed -i "s/# db_key_base:/db_key_base: ${gitlab_app_secret}/" ${gitlab_app_root}/config/secrets.yml
  echo ${gitlab_app_secret} > ${gitlab_app_root}/.secret
  }

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'
  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"
  su ${gitlab_user} -s /bin/sh -c 'bundle exec rake db:migrate'
fi

# Restrict permissions for secret files
chown ${gitlab_user}: ${gitlab_data_dir}/.secret
chmod 0700 ${gitlab_data_dir}/.secret
chmod 0700 ${gitlab_data_dir}/.gitlab_shell_secret
chown ${gitlab_user}: ${gitlab_app_root}/config/secrets.yml
chmod 0700 ${gitlab_app_root}/config/secrets.yml


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

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

