#!/usr/bin/env bash # medusa-deploy, from https://exe.dev/deploy/medusa # Builds the last commit of ~/store into a new release in ~/releases: the # Medusa server and admin first (backup, migrations, restart), then the # Next.js storefront, which needs the new server running to build. # ~/current is the live server release, ~/current-storefront the live # storefront's. Keeps three releases. # medusa-deploy build and switch to HEAD of ~/store # medusa-deploy --rollback both back to the previous release (no migrations) set -euo pipefail releases="$HOME/releases" mkdir -p "$releases" wait_for() { # url, unit for i in $(seq 1 90); do curl -fs -o /dev/null "$1" && return 0; sleep 2; done echo "$1 is not answering: journalctl -u $2" >&2; exit 1 } switch_server() { ln -sfn "$1" "$HOME/current" sudo systemctl restart medusa wait_for http://localhost:9000/health medusa } switch_storefront() { ln -sfn "$1" "$HOME/current-storefront" sudo systemctl restart storefront wait_for http://localhost:8000/ storefront } if [ "${1:-}" = "--rollback" ]; then current=$(readlink -f "$HOME/current") previous=$(ls -1d "$releases"/*/ | sed 's#/$##' | grep -vx "$current" | tail -n 1) [ -n "$previous" ] || { echo "No earlier release to go back to." >&2; exit 1; } switch_server "$previous" switch_storefront "$previous" echo "Live: $previous" exit 0 fi cd "$HOME/store" [ -z "$(git status --porcelain)" ] || echo "Note: uncommitted changes in ~/store are not deployed." >&2 rev=$(git rev-parse --short HEAD) rel="$releases/$(date +%Y%m%d-%H%M%S)-$rev" mkdir -p "$rel" git archive HEAD | tar -x -C "$rel" echo "== Installing packages" cd "$rel" pnpm install --frozen-lockfile --prefer-offline echo "== Building Medusa and the admin" cd "$rel/apps/backend" ( set -a; . "$HOME/medusa.env"; set +a; pnpm exec medusa build ) ln -sfn "$HOME/medusa-data/static" .medusa/server/static echo "== Backing up, then migrating the database" "$HOME/bin/medusa-backup" ( cd .medusa/server; set -a; . "$HOME/medusa.env"; set +a; ../../node_modules/.bin/medusa db:migrate ) # The first migration creates the store's publishable API key, which the # storefront needs at build time. if ! grep -q '^NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=pk_' "$HOME/storefront.env"; then key=$(set -a; . "$HOME/medusa.env"; psql "$DATABASE_URL" -Atc \ "SELECT token FROM api_key WHERE type = 'publishable' AND revoked_at IS NULL AND deleted_at IS NULL ORDER BY created_at LIMIT 1") sed -i "s/^NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=.*/NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=$key/" "$HOME/storefront.env" fi echo "== Switching the server" switch_server "$rel" echo "== Building the storefront" cd "$rel/apps/storefront" ln -sfn "$HOME/storefront.env" .env.production.local pnpm exec next build echo "== Switching the storefront" switch_storefront "$rel" echo "Live: $rel" keep=$(readlink -f "$HOME/current") ls -1d "$releases"/*/ | sed 's#/$##' | head -n -3 | { grep -vx "$keep" || true; } | xargs -r rm -rf