#!/usr/bin/env bash
# Compare pages on the VM with the same pages on Railway: status code,
# redirect, and
, for each path in ~/railway/paths.txt.
# From https://exe.dev/deploy/migrate-railway
#
# railway/check ask Railway now, and save its answers
# railway/check --saved compare with the saved answers (Railway is stopped)
set -uo pipefail
rw=~/railway
[ -f $rw/paths.txt ] || echo / > $rw/paths.txt
railway=$(cat $rw/railway-url)
host=$(hostname).exe.xyz
answer() { # URL [curl options]: "status redirect title"
local url=$1 out title=''; shift
out=$(curl -sS -o /tmp/check.body -w '%{http_code} %{redirect_url}' --max-time 20 "$@" "$url" 2>/dev/null |
sed "s#https\?://[^/]*##")
# Error pages often come from the platform rather than the app, so
# titles are compared only for pages that answer 2xx.
case $out in 2*) title=$(grep -o -i ']*>[^<]*' /tmp/check.body | head -1 | sed 's/<[^>]*>//') ;; esac
printf '%s %s\n' "$out" "$title"
}
[ "${1:-}" = --saved ] || : > $rw/answers.txt.new
diffs=0
while read -r path; do
[ -n "$path" ] || continue
if [ "${1:-}" = --saved ]; then
theirs=$(awk -F'\t' -v p="$path" '$1 == p { print $2; exit }' $rw/answers.txt)
else
theirs=$(answer "$railway$path")
printf '%s\t%s\n' "$path" "$theirs" >> $rw/answers.txt.new
fi
ours=$(answer "http://localhost:8000$path" -H "Host: $host" -H "X-Forwarded-Proto: https")
if [ "$theirs" = "$ours" ]; then
echo "same $path ($ours)"
else
echo "DIFFERENT $path Railway: $theirs VM: $ours"; diffs=$((diffs + 1))
fi
done < $rw/paths.txt
if [ "${1:-}" != --saved ]; then
# Keep the last good answers if Railway didn't answer (stopped, at the move).
if cut -f2 $rw/answers.txt.new | grep -q '^000'; then
echo "Railway didn't answer every page; kept the answers saved before."
rm -f $rw/answers.txt.new
else
mv $rw/answers.txt.new $rw/answers.txt
fi
fi
exit $((diffs > 0))