#!/usr/bin/env bash # Build ~/app and make it the live site at https://.exe.xyz/. # Each publish is a new directory in /var/www/app/releases; nginx serves # /var/www/app/current/dist, and api.service runs current/server. # If the new release doesn't answer, the previous one is put back. # Go back to the release before the current one: ~/bin/publish --rollback set -euo pipefail base=/var/www/app previous=$(readlink "$base/current" || true) switch() { # point current at $1 and restart the API if the release has one ln -sfn "$1" "$base/current.new" && mv -T "$base/current.new" "$base/current" if [ -f "$1/server/index.ts" ]; then sudo systemctl restart api; fi } check() { # the page and, if there is one, the API answer local i for i in $(seq 20); do if curl -fs -o /dev/null http://127.0.0.1:8000/ && { [ ! -f "$base/current/server/index.ts" ] || curl -fs -o /dev/null http://127.0.0.1:8000/api/health; }; then return 0 fi sleep 0.5 done return 1 } if [ "${1:-}" = --rollback ]; then target=$(ls -1d "$base"/releases/*/ | sed 's:/$::' | awk -v cur="$previous" '$0 < cur' | tail -n 1) [ -n "$target" ] || { echo "No other release to roll back to."; exit 1; } switch "$target" && check echo "Rolled back to $target" exit 0 fi cd ~/app npm run build release=$base/releases/$(date -u +%Y%m%d-%H%M%S) mkdir -p "$release" cp -a dist "$release/dist" if [ -f server/index.ts ]; then cp -a server package.json package-lock.json "$release/" (cd "$release" && npm ci --omit=dev --no-audit --no-fund --loglevel=error) fi switch "$release" if ! check; then echo "The new release doesn't answer (journalctl -u api -u nginx); putting back ${previous:-nothing}." if [ -n "$previous" ]; then switch "$previous"; else rm -f "$base/current"; fi rm -rf "$release" exit 1 fi ls -1d "$base"/releases/*/ | head -n -3 | xargs -r rm -rf # keep the newest 3 echo "Published $(basename "$release"): https://$(hostname).exe.xyz/"