#!/usr/bin/env bash
# Restore only the exact file changed by VWCG-1357; never overwrite an unrelated version.
set -euo pipefail
root=/workspace/wwwroot/zhct_jsr/project
target="$root/application/p/logic/MealOrder.php"
backup_dir=/workspace/wwwroot/zhct_jsr/hotfix-backups/VWCG-1357-receipt-date
backup="$backup_dir/MealOrder.php.before"
old_hash=d4805ec00a7cea47131a06d6e2a1d3258bd6b28f15938e65ebb8952fd16899e1
new_hash=089df04e521f98aca802ade3bc51e9c9ab13857894a9c7558a9b73723a5a11fd
php=/usr/local/php7.3/bin/php
case "$(hostname)" in iZ2zeawufz0876gxr3k5fwZ|iZ2ze12juwl7c3y6h920e8Z) ;; *) exit 10 ;; esac
[[ "$(readlink -f "$root")" == "$root" && "$(readlink -f "$target")" == "$target" ]]
[[ -f "$target" && ! -L "$target" && -f "$backup" && ! -L "$backup" ]]
[[ "$(readlink -f "$backup_dir")" == "$backup_dir" ]]
grep -Fq "define('BUSINESS', 'zhct_jsr');" "$root/env.php"
exec 9>"$backup_dir/deploy.lock"
flock -n 9
hash_file() { sha256sum "$1" | awk '{print $1}'; }
[[ "$(hash_file "$backup")" == "$old_hash" ]]
current=$(hash_file "$target")
if [[ "$current" == "$old_hash" ]]; then printf 'ALREADY_ROLLED_BACK\n'; exit 0; fi
[[ "$current" == "$new_hash" ]] || { printf 'Unexpected current file; rollback refused\n' >&2; exit 11; }
staged=$(mktemp "$root/application/p/logic/.MealOrder.php.VWCG-1357-rollback.XXXXXX")
trap '[[ ! -e "$staged" ]] || rm -f "$staged"' EXIT
cp -p "$backup" "$staged"
"$php" -l "$staged"
[[ "$(hash_file "$staged")" == "$old_hash" && "$(hash_file "$target")" == "$new_hash" ]]
mv -f "$staged" "$target"
[[ "$(hash_file "$target")" == "$old_hash" ]]
printf 'ROLLBACK_RESTORED %s\n' "$old_hash"
