#!/usr/bin/env bash
# Deploys one release of the platform's sandbox (ADR-0012) on the Hestia server: user rebonus, sandbox.rebonus.ru.
# Runs as root. Usage: deploy.sh <sha> <code.tar.gz> <builds.tar.gz> [first]
#   first - also writes the shared .env with new secrets and creates the database roles (once).
# Secrets are generated here and never printed. Hestia objects (users, domains, SSL, cron) are made with v-* only.
set -euo pipefail

SHA="$1"
CODE="$2"
BUILDS="$3"
FIRST="${4:-}"

OWNER=rebonus
PHP=/usr/bin/php8.5
COMPOSER=/usr/local/bin/composer
WEB=/home/rebonus/web/sandbox.rebonus.ru
BASE="$WEB/private/sandbox"
REL="$BASE/releases/$SHA"
SHARED="$BASE/shared"
DATABASE=rebonus_sandbox

as_owner() {
	(cd "$REL" && runuser -u "$OWNER" -- env HOME=/home/rebonus COMPOSER_HOME=/home/rebonus/.composer "$@")
}

if [ -e "$REL" ]; then
	echo "release $SHA is there already" >&2
	exit 1
fi

echo "== unpack $SHA"
mkdir -p "$REL" "$SHARED"
tar -xzf "$CODE" -C "$REL"
tar -xzf "$BUILDS" -C "$REL"

if [ ! -d "$SHARED/storage" ]; then
	cp -a "$REL/storage" "$SHARED/storage"
fi
rm -rf "$REL/storage"
ln -s "$SHARED/storage" "$REL/storage"
ln -s "$SHARED/.env" "$REL/.env"

if [ "$FIRST" = "first" ]; then
	if [ -e "$SHARED/.env" ]; then
		echo "the shared .env exists: not a first deploy" >&2
		exit 1
	fi
	echo "== write the shared .env"
	cat >"$SHARED/.env" <<'ENV'
APP_NAME="Rebonus Sandbox"
APP_ENV=sandbox
APP_KEY=
APP_DEBUG=false
APP_URL=https://sandbox.rebonus.ru

# Sandbox for integrators (ADR-0012): its own database, keys and host.
LOYAL_SANDBOX=true
LOYAL_TRAFFIC=all
LOYAL_PROCESSOR_NAME=
LOYAL_PROCESSOR_ADDRESS=

ACCESS_RATE_PER_KEY_PER_MINUTE=60
ACCESS_RATE_PER_TENANT_PER_MINUTE=120
ACCESS_MANAGEMENT_RATE_PER_MINUTE=60
VERIFICATION_TENANT_DAILY_LIMIT=500

APP_LOCALE=ru
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=ru_RU
APP_MAINTENANCE_DRIVER=file
HASH_DRIVER=argon2id

LOG_CHANNEL=stack
LOG_STACK=daily
LOG_DAILY_DAYS=14
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=info

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=rebonus_sandbox
DB_USERNAME=loyal_app
DB_PASSWORD=__APP__
DB_OWNER_USERNAME=loyal_owner
DB_OWNER_PASSWORD=__OWNER__
DB_SYSTEM_USERNAME=loyal_system
DB_SYSTEM_PASSWORD=__SYSTEM__
# Only while db:bootstrap runs on the first deploy.
DB_SUPERUSER_USERNAME=postgres
DB_SUPERUSER_PASSWORD=

PII_ENCRYPTION_KEYS=
PII_BLIND_INDEX_KEY=

SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=true
SESSION_PATH=/
SESSION_DOMAIN=null
SESSION_SECURE_COOKIE=true

CONSOLE_DOMAIN=console.sandbox.rebonus.ru

BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database

# Staff mail stays in the log until rebonus.ru has its mail records (SPF, DKIM).
MAIL_MAILER=log
# sendmail in -t mode: Hestia's exim refuses the SMTP dialogue of the default -bs, whose HELO is [127.0.0.1]
# ("550 HELO contains an IP address and does not match PTR").
MAIL_SENDMAIL_PATH="/usr/sbin/sendmail -t -i"
MAIL_FROM_ADDRESS="noreply@rebonus.ru"
MAIL_FROM_NAME="Rebonus"
ENV
	sed -i \
		-e "s/__APP__/$(openssl rand -hex 24)/" \
		-e "s/__OWNER__/$(openssl rand -hex 24)/" \
		-e "s/__SYSTEM__/$(openssl rand -hex 24)/" \
		"$SHARED/.env"
	chmod 600 "$SHARED/.env"
fi

chown -R "$OWNER:$OWNER" "$BASE"
chown -h "$OWNER:$OWNER" "$REL/storage" "$REL/.env"

echo "== composer install"
as_owner "$PHP" "$COMPOSER" install --no-dev --prefer-dist --no-interaction --no-progress --optimize-autoloader 2>&1 | tail -5

if [ "$FIRST" = "first" ]; then
	echo "== keys"
	as_owner "$PHP" artisan key:generate --force
	as_owner "$PHP" artisan pii:generate-keys

	echo "== database roles (superuser password only for this step)"
	reset_superuser() {
		printf 'alter role postgres with password null;\n' | runuser -u postgres -- psql -q -v ON_ERROR_STOP=1
		sed -i 's/^DB_SUPERUSER_PASSWORD=.*/DB_SUPERUSER_PASSWORD=/' "$SHARED/.env"
	}
	trap reset_superuser EXIT
	su_password="$(openssl rand -hex 24)"
	printf "alter role postgres with password '%s';\n" "$su_password" | runuser -u postgres -- psql -q -v ON_ERROR_STOP=1
	sed -i "s/^DB_SUPERUSER_PASSWORD=.*/DB_SUPERUSER_PASSWORD=$su_password/" "$SHARED/.env"
	unset su_password
	as_owner "$PHP" artisan db:bootstrap --database="$DATABASE" --force
	reset_superuser
	trap - EXIT
fi

echo "== migrate"
as_owner "$PHP" artisan migrate --database=pgsql_owner --force

echo "== caches"
as_owner "$PHP" artisan config:cache
as_owner "$PHP" artisan route:cache
as_owner "$PHP" artisan event:cache
as_owner "$PHP" artisan view:cache

echo "== switch to $SHA"
ln -sfn "$REL" "$BASE/current.new"
chown -h "$OWNER:$OWNER" "$BASE/current.new"
mv -T "$BASE/current.new" "$BASE/current"
# The pool has no open_basedir (template rebonus-PHP-8_5), so PHP's workers keep the paths they resolved through
# `current` in their realpath cache: only the workers the reload starts see the new release.
systemctl reload php8.5-fpm
if systemctl is-enabled --quiet rebonus-sandbox-queue 2>/dev/null; then
	(cd "$BASE/current" && runuser -u "$OWNER" -- "$PHP" artisan queue:restart)
fi

echo "== keep the last three releases"
# releases/ is the user's: real folders only, named without a trailing slash, so that a link it planted there takes
# root nowhere else.
find "$BASE/releases" -mindepth 1 -maxdepth 1 -type d -printf '%T@\t%p\n' | sort -rn | tail -n +4 | cut -f2- |
	xargs -r -d '\n' rm -rf --

echo "== done: $(readlink "$BASE/current")"
