#!/usr/bin/env bash
# Run from the bos-api application repository root, not the website repository.
set -euo pipefail
umask 077
mkdir -p .dev
if [[ -e .dev/backend.env ]]; then
  printf 'Keep the existing .dev/backend.env and encryption key. Configuration was not replaced.\n' >&2
  exit 1
fi

mysql_password=$(openssl rand -hex 24)
mysql_root_password=$(openssl rand -hex 24)
redis_password=$(openssl rand -hex 24)
encryption_key=$(openssl rand -base64 32)
jwt_key=$(openssl rand -hex 32)
admin_password=$(openssl rand -hex 24)

cat > .dev/backend.env <<ENV
MYSQL_DATABASE=bosapi_dev
MYSQL_USER=bosapi_dev
MYSQL_PASSWORD=$mysql_password
MYSQL_ROOT_PASSWORD=$mysql_root_password
REDIS_PASSWORD=$redis_password
BOS_LISTEN=127.0.0.1:8081
BOS_CALLBACK_LISTEN=127.0.0.1:1455
BOS_DATA_FILE=../.dev/gateway.enc
BOS_ENCRYPTION_KEY=$encryption_key
BOS_DATABASE_DSN='bosapi_dev:$mysql_password@tcp(127.0.0.1:13307)/bosapi_dev?charset=utf8mb4&parseTime=true&loc=UTC'
BOS_REDIS_URL=redis://:$redis_password@127.0.0.1:16380/0
BOS_JWT_SIGNING_KEY=$jwt_key
BOS_ADMIN_EMAIL=admin@bosapi.local
BOS_ADMIN_PASSWORD=$admin_password
BOS_WEB_DIR=
BOS_MAX_REQUEST_BODY_MB=128
BOS_GATEWAY_TIMEOUT_SECONDS=300
BOS_USAGE_REPORTING_FORCE_DISABLED=true
TZ=Asia/Shanghai
ENV
chmod 600 .dev/backend.env
printf 'Created .dev/backend.env (mode 600). Read initial administrator credentials privately from this file.\n'
