#!/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=${ZHCT_PROJECT_DIR:-/workspace/wwwroot/zhct_sanquan/project}
STATE=${ZHCT_RELEASE_STATE_DIR:-/workspace/wwwroot/zhct_sanquan/releases}
release_init zhct_sanquan "$VERSION" zhct "$TARGET" "$STATE"
release_extract
for file in think env.php composer.json application/config/prod/zhct_sanquan/config.php application/config/prod/zhct_sanquan/database.php; do
    release_require_stage_file "$file"
done
grep -Fq "define('BUSINESS', 'zhct_sanquan')" "$RELEASE_STAGE/env.php" || release_die 'Store BUSINESS is not zhct_sanquan'
STORE_CONFIG="$RELEASE_STAGE/application/config/prod/zhct_sanquan/config.php"
STORE_DATABASE="$RELEASE_STAGE/application/config/prod/zhct_sanquan/database.php"
store_redis=$(awk '/\$config\['\''redis'\''\][[:space:]]*=/{show=1} show{print} show && /^[[:space:]]*\];/{exit}' "$STORE_CONFIG")
grep -Eq "'host'[[:space:]]*=>[[:space:]]*'10\.2\.203\.117'" <<<"$store_redis" || release_die 'Store Redis VIP mismatch'
grep -Eq "'port'[[:space:]]*=>[[:space:]]*6379" <<<"$store_redis" || release_die 'Store Redis port mismatch'
if grep -Eq "'select'[[:space:]]*=>" <<<"$store_redis"; then
    grep -Eq "'select'[[:space:]]*=>[[:space:]]*0([,[:space:]]|$)" <<<"$store_redis" || release_die 'Store Redis database must be DB0'
fi
grep -Fq "\$config['hostname'] = '10.2.203.117';" "$STORE_DATABASE" || release_die 'Store MySQL VIP mismatch'
grep -Fq "\$config['hostport'] = '3306';" "$STORE_DATABASE" || release_die 'Store MySQL port mismatch'
grep -Fq "\$config['database'] = 'zhct_sanquan';" "$STORE_DATABASE" || release_die 'Store database name mismatch'
grep -Eq "'database'[[:space:]]*=>[[:space:]]*'aizhct_sanquan'" "$STORE_DATABASE" || release_die 'Store AI database name mismatch'
release_preserve_path public/static/upload
release_preserve_path public/store
release_ensure_stage_dir public/static/upload
release_write_metadata
release_set_permissions
release_switch
release_reload_fpm php-fpm73.service
release_restart_supervisor_groups meal_order_zhct_sanquan qw_robot_zhct_sanquan consume_zhct_sanquan pushDishes_zhct_sanquan
release_apply_file_policy
release_finish
