#!/usr/bin/env bash
# Deploys one release of the platform's production for the pilot on the Hestia server (the owner's call, 2026-11-18:
# the pilot stays on the company's server, a cloud comes with growth): user rebonusapp, app.rebonus.ru with the console,
# the customer portal, the web till and the captcha box as its aliases, PostgreSQL's own instance `prod` on port 5433.
# Runs as root. Usage: deploy.sh <sha> <code.tar.gz> <builds.tar.gz> [first]
#   first - also writes the shared .env with new secrets, creates the database roles and the backup role, and keeps a
#           copy of the keys for the owner in /root/rebonus-deploy/production-keys.txt (root only), 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=rebonusapp
PHP=/usr/bin/php8.5
COMPOSER=/usr/local/bin/composer
WEB=/home/rebonusapp/web/app.rebonus.ru
BASE="$WEB/private/app"
REL="$BASE/releases/$SHA"
SHARED="$BASE/shared"
DATABASE=rebonus
PGPORT=5433
KEYS=/root/rebonus-deploy/production-keys.txt

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

as_postgres() {
	runuser -u postgres -- psql -p "$PGPORT" -q -v ON_ERROR_STOP=1 "$@"
}

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
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=https://app.rebonus.ru

LOYAL_SANDBOX=false
LOYAL_TRAFFIC=all
LOYAL_PROCESSOR_NAME="ИП Верховых Евгений Андреевич"
LOYAL_PROCESSOR_ADDRESS="423827, Республика Татарстан, г. Набережные Челны, а/я 27115"

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

# PostgreSQL's own instance for production (port 5433): its roles are none of the sandbox's.
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5433
DB_DATABASE=rebonus
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
SESSION_COOKIE=__Host-loyal_session

CONSOLE_DOMAIN=console.rebonus.ru
CABINET_TIMEZONE=Europe/Moscow
TILL_DOMAIN=kassa.rebonus.ru
PORTAL_DOMAIN=card.rebonus.ru
PORTAL_CAPTCHA_DOMAIN=check.rebonus.ru
# Yandex SmartCaptcha's keys from the owner: without them the portal sends no codes.
PORTAL_CAPTCHA_CLIENT_KEY=
PORTAL_CAPTCHA_SERVER_KEY=

MOYSKLAD_APP_ID=
MOYSKLAD_APP_UID=
MOYSKLAD_SECRET_KEY=

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

# sendmail in -t mode: Hestia's exim refuses the SMTP dialogue of the default -bs, whose HELO is [127.0.0.1].
MAIL_MAILER=sendmail
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 (the superuser's password only for this step)"
	reset_superuser() {
		printf 'alter role postgres with password null;\n' | as_postgres
		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" | as_postgres
	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

	echo "== the backup role: reads every row, changes nothing"
	backup_password="$(openssl rand -hex 24)"
	# db:bootstrap takes CONNECT from PUBLIC: the backup role is given it by name.
	printf "create role loyal_backup login bypassrls password '%s';\ngrant pg_read_all_data to loyal_backup;\ngrant connect on database %s to loyal_backup;\n" "$backup_password" "$DATABASE" | as_postgres
	install -o "$OWNER" -g "$OWNER" -m 600 /dev/null /home/rebonusapp/.pgpass
	printf '127.0.0.1:%s:%s:loyal_backup:%s\n' "$PGPORT" "$DATABASE" "$backup_password" >/home/rebonusapp/.pgpass
	unset backup_password

	echo "== a copy of the keys for the owner (root only): without them the backups' phones and e-mails cannot be read"
	install -m 600 /dev/null "$KEYS"
	{
		echo "Rebonus production ($(date -I)): keep these in the password manager; the backups leave the .env out."
		grep -E '^(APP_KEY|PII_ENCRYPTION_KEYS|PII_BLIND_INDEX_KEY)=' "$SHARED/.env"
	} >"$KEYS"
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-app-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")"
