#!/usr/bin/env bash

set -e

RAILS_ENV=development

if [ -f tmp/pids/server.pid ]; then
  kill $(cat tmp/pids/server.pid)
fi

bundle install
# Generate seed files.
bin/init_config
# Drop and create peatio_development and peatio_test databases.
bundle exec rails db:drop db:create
# Set the current RAILS_ENV environment in the ar_internal_metadata table.
# (Used as part of the protected environment check.)
bin/rails db:environment:set RAILS_ENV=$RAILS_ENV
# Runs migrations for the current environment that have not run yet.
bundle exec rails db:migrate
# Runs the db/seeds.rb file.
bundle exec rails db:seed

npm i -g swagger-markdown
bundle exec rails s -d
while [ ! -f tmp/pids/server.pid ]
do
  sleep 1
done
sleep 5 # Wait additional time until Rails starts listen port.

curl http://localhost:3000/api/v2/swagger > tmp/user_api_v2_swagger.json
curl http://localhost:3000/api/v2/management/swagger > tmp/management_api_v2_swagger.json
curl http://localhost:3000/api/v2/admin/swagger > tmp/admin_api_v2_swagger.json

mkdir -p docs/api/swagger

swagger-markdown -i tmp/user_api_v2_swagger.json -o ./docs/api/peatio_user_api_v2.md
swagger-markdown -i tmp/management_api_v2_swagger.json -o ./docs/api/peatio_management_api_v2.md
swagger-markdown -i tmp/admin_api_v2_swagger.json -o ./docs/api/peatio_admin_api_v2.md

ruby -r json -e "puts JSON.pretty_generate(JSON.parse(File.read('tmp/user_api_v2_swagger.json')))" \
      > docs/api/swagger/user_api.json
ruby -r json -e "puts JSON.pretty_generate(JSON.parse(File.read('tmp/management_api_v2_swagger.json')))" \
      > docs/api/swagger/management_api.json
ruby -r json -e "puts JSON.pretty_generate(JSON.parse(File.read('tmp/admin_api_v2_swagger.json')))" \
      > docs/api/swagger/admin_api.json

kill $(cat tmp/pids/server.pid)
