#!/usr/bin/env bash

set -Eeuo pipefail

if [[ $# -lt 1 || $# -gt 2 ]]; then
    echo "usage: $0 VERSION [--dry-run]" >&2
    exit 2
fi
VERSION=$1
[[ "${2:-}" == '--dry-run' ]] && DRY_RUN=1
[[ $# -eq 1 || "${2:-}" == '--dry-run' ]] || { echo "unknown option: ${2:-}" >&2; exit 2; }

RELEASE_SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=release-common.sh
source "$RELEASE_SCRIPT_DIR/release-common.sh"

TARGET=${AIZHCT_PROJECT_DIR:-/workspace/wwwroot/aizhct_sanquan/project}
STATE=${AIZHCT_RELEASE_STATE_DIR:-/workspace/wwwroot/aizhct_sanquan/releases}
release_init aizhct_sanquan "$VERSION" aizhct "$TARGET" "$STATE"
release_extract
for file in think env.php composer.json .env.prodaizhct_sanquan config/filesystem.php; do
    release_require_stage_file "$file"
done
grep -Fq "define('BUSINESS', 'aizhct_sanquan')" "$RELEASE_STAGE/env.php" || release_die 'AI BUSINESS is not aizhct_sanquan'
AI_ENV="$RELEASE_STAGE/.env.prodaizhct_sanquan"
ai_database=$(awk '/^\[DATABASE\][[:space:]]*$/{show=1; next} /^\[/{if(show) exit} show{print}' "$AI_ENV")
ai_redis=$(awk '/^\[REDIS\][[:space:]]*$/{show=1; next} /^\[/{if(show) exit} show{print}' "$AI_ENV")
grep -Eq '^HOSTNAME[[:space:]]*=[[:space:]]*10\.2\.203\.117[[:space:]]*$' <<<"$ai_database" || release_die 'AI MySQL VIP mismatch'
grep -Eq '^HOSTPORT[[:space:]]*=[[:space:]]*3306[[:space:]]*$' <<<"$ai_database" || release_die 'AI MySQL port mismatch'
grep -Eq '^DATABASE[[:space:]]*=[[:space:]]*aizhct_sanquan[[:space:]]*$' <<<"$ai_database" || release_die 'AI database name mismatch'
grep -Eq '^HOSTNAME[[:space:]]*=[[:space:]]*10\.2\.203\.117[[:space:]]*$' <<<"$ai_redis" || release_die 'AI Redis VIP mismatch'
grep -Eq '^HOSTPORT[[:space:]]*=[[:space:]]*6379[[:space:]]*$' <<<"$ai_redis" || release_die 'AI Redis port mismatch'
if grep -Eq '^SELECT[[:space:]]*=' <<<"$ai_redis"; then
    grep -Eq '^SELECT[[:space:]]*=[[:space:]]*0[[:space:]]*$' <<<"$ai_redis" || release_die 'AI Redis database must be DB0'
fi
install -m 0640 "$AI_ENV" "$RELEASE_STAGE/.env"
release_preserve_path public/uploads
release_preserve_path public/downloads
release_ensure_stage_dir public/uploads
release_ensure_stage_dir public/downloads
release_write_metadata
release_set_permissions
release_switch
release_reload_fpm php-fpm74.service
release_restart_supervisor_groups aistaffpower_sanquan aizhcttime_sanquan
release_apply_file_policy
release_finish
