Files
fewo-stommer/scripts/deploy.sh
T

258 lines
10 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
#
# Deployment to Strato (or any SSH host offering bash, tar and a PHP CLI) with atomic releases.
#
# scripts/deploy.sh <environment> setup create the folder structure on the server (once)
# scripts/deploy.sh <environment> deploy build, upload, migrate, switch, health check (rollback on failure)
# scripts/deploy.sh <environment> rollback switch back to the previous release
# scripts/deploy.sh <environment> releases list releases on the server
# scripts/deploy.sh <environment> artisan <args> run an artisan command in the active release
#
# Settings come from scripts/deploy.<environment>.env (not committed, see scripts/deploy.example.env)
# or from environment variables (CI). Server layout below DEPLOY_PATH:
#
# releases/<timestamp>/ one folder per release (code, vendor, built assets)
# shared/.env production settings – created by hand once
# shared/storage/ uploads, logs, sessions, cache – survive every release
# current -> releases/… active release (CLI, cron); the domain points at DEPLOY_PATH, whose .htaccess
# forwards to the active release's public folder
#
set -euo pipefail
ENVIRONMENT="${1:?Bitte Umgebung angeben, z. B.: scripts/deploy.sh production deploy}"
COMMAND="${2:-deploy}"
shift $(($# >= 2 ? 2 : 1))
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CONFIG="$ROOT/scripts/deploy.$ENVIRONMENT.env"
if [[ -f "$CONFIG" ]]; then
# shellcheck source=/dev/null
source "$CONFIG"
fi
: "${DEPLOY_HOST:?DEPLOY_HOST fehlt (z. B. ssh.strato.de oder local)}"
: "${DEPLOY_PATH:?DEPLOY_PATH fehlt (Ordner auf dem Server, z. B. fewo-production)}"
DEPLOY_USER="${DEPLOY_USER:-}"
DEPLOY_PORT="${DEPLOY_PORT:-22}"
DEPLOY_PHP="${DEPLOY_PHP:-/opt/RZphp84/bin/php-cli}"
DEPLOY_KEEP="${DEPLOY_KEEP:-5}"
DEPLOY_URL="${DEPLOY_URL:-}"
DEPLOY_SSH_KEY="${DEPLOY_SSH_KEY:-}"
DEPLOY_SSH_KEY="${DEPLOY_SSH_KEY/#\~/$HOME}"
COMPOSER_BIN="${COMPOSER_BIN:-composer}"
say() { printf '\n\033[1;34m▶ %s\033[0m\n' "$*"; }
fail() { printf '\n\033[1;31m✗ %s\033[0m\n' "$*" >&2; exit 1; }
# The script executed on the server. Arguments: <base path> <php binary> <command> [args…]
remote_script() {
cat <<'REMOTE'
set -euo pipefail
base="$1"; php="$2"; cmd="$3"; shift 3
mkdir -p "$base"
cd "$base"
# The web is served from the concrete release folder, not through the "current" symlink: Strato's
# OPcache keys scripts by the symlinked path and would keep serving the previous release.
# Strato: the web server's PHP version can be chosen per folder; use the same version as the CLI.
write_htaccess() {
local target="$1"
local web_php
web_php="$(printf '%s' "$php" | grep -oE 'RZphp[0-9]+' | grep -oE '[0-9]+' || true)"
{ [[ -n "$web_php" ]] && echo "AddType application/x-httpd-php$web_php .php"; cat <<HTACCESS
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(releases/(?!$target/public/)|shared(/|$)|current(/|$)|\.|upload-) - [F,L]
RewriteCond %{REQUEST_URI} !^/releases/$target/public/
RewriteRule ^(.*)\$ releases/$target/public/\$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
Require all denied
</IfModule>
HTACCESS
} > .htaccess.new
mv -f .htaccess.new .htaccess
}
switch_to() {
ln -sfn "$1" current.new
mv -Tf current.new current
write_htaccess "$(basename "$1")"
}
case "$cmd" in
setup)
mkdir -p releases shared/storage/app/public shared/storage/framework/cache/data shared/storage/framework/sessions shared/storage/framework/views shared/storage/logs
# For hosting panels that cannot point a domain at a symlink: the domain points at this folder,
# .htaccess forwards to the active release's public folder and blocks all internal files.
active="$(readlink current 2>/dev/null || true)"
if [[ -n "$active" ]]; then write_htaccess "$(basename "$active")"; else printf 'Require all denied
' > .htaccess; fi
echo ".htaccess angelegt (Domain-Ziel: $base)."
if [[ -f shared/.env ]]; then echo "shared/.env vorhanden."; else echo "HINWEIS: Bitte $base/shared/.env anlegen (Vorlage: .env.production.example)."; fi
echo "PHP: $("$php" -v | head -n 1)"
;;
receive)
release="$1"
mkdir -p "releases/$release"
tar -xzf "upload-$release.tgz" -C "releases/$release"
rm -f "upload-$release.tgz"
;;
activate)
release="$1"; keep="$2"; dir="releases/$release"
[[ -f shared/.env ]] || { echo "shared/.env fehlt – erst anlegen (siehe docs/DEPLOYMENT.md)." >&2; exit 1; }
rm -rf "$dir/storage"
ln -s ../../shared/storage "$dir/storage"
ln -sfn ../../shared/.env "$dir/.env"
mkdir -p "$dir/bootstrap/cache"
ln -sfn ../storage/app/public "$dir/public/storage"
(
cd "$dir"
"$php" artisan migrate --force --no-interaction
"$php" artisan optimize --no-interaction
"$php" artisan filament:optimize --no-interaction >/dev/null 2>&1 || true
)
readlink current > .previous_release 2>/dev/null || true
switch_to "$dir"
ls -1d releases/* | sort | head -n -"$keep" | xargs -r rm -rf
echo "Aktiv: $release"
;;
rollback)
active="$(readlink current 2>/dev/null || true)"
target="$(cat .previous_release 2>/dev/null || true)"
if [[ -z "$target" || "$target" == "$active" || ! -d "$target" ]]; then
target="$(ls -1d releases/* | sort | grep -vx "$active" | tail -n 1 || true)"
fi
[[ -n "$target" && -d "$target" ]] || { echo "Keine frühere Version vorhanden." >&2; exit 1; }
switch_to "$target"
echo "$active" > .previous_release
echo "Zurückgeschaltet auf: $target (Datenbank-Migrationen werden dabei nicht zurückgenommen)"
;;
releases)
ls -1 releases
echo "Aktiv: $(readlink current 2>/dev/null || echo '–')"
;;
artisan)
cd current
"$php" artisan "$@"
;;
*)
echo "Unbekannter Befehl: $cmd" >&2; exit 1
;;
esac
REMOTE
}
run_remote() {
if [[ "$DEPLOY_HOST" == "local" ]]; then
bash -s -- "$DEPLOY_PATH" "$DEPLOY_PHP" "$@"
else
local ssh_args=(-p "$DEPLOY_PORT" -o BatchMode=yes -o ServerAliveInterval=30)
[[ -n "$DEPLOY_SSH_KEY" ]] && ssh_args+=(-i "$DEPLOY_SSH_KEY")
ssh "${ssh_args[@]}" "${DEPLOY_USER:+$DEPLOY_USER@}$DEPLOY_HOST" bash -s -- "$DEPLOY_PATH" "$DEPLOY_PHP" "$@"
fi
}
# Runs the remote script (sent via stdin) with the given command.
remote() {
run_remote "$@" < <(remote_script)
}
# Copies the release archive to <DEPLOY_PATH>/upload-<release>.tgz on the server.
upload() {
local archive="$1" release="$2"
if [[ "$DEPLOY_HOST" == "local" ]]; then
mkdir -p "$DEPLOY_PATH"
cp "$archive" "$DEPLOY_PATH/upload-$release.tgz"
else
local ssh_args=(-p "$DEPLOY_PORT" -o BatchMode=yes)
[[ -n "$DEPLOY_SSH_KEY" ]] && ssh_args+=(-i "$DEPLOY_SSH_KEY")
ssh "${ssh_args[@]}" "${DEPLOY_USER:+$DEPLOY_USER@}$DEPLOY_HOST" "mkdir -p '$DEPLOY_PATH' && cat > '$DEPLOY_PATH/upload-$release.tgz'" < "$archive"
fi
}
# Strato limits the number of files per package (inode quota), and every release carries ~19,000 files.
# Removes what the application never loads at runtime: translations other than de/en, tests and docs.
prune_vendor() {
local before
before="$(find vendor -type f | wc -l)"
find vendor -mindepth 5 -maxdepth 5 -type d -path '*/resources/lang/*' ! -name de ! -name en -exec rm -rf {} +
find vendor/nesbot/carbon/src/Carbon/Lang -type f ! -name 'de*' ! -name 'en*' -delete 2>/dev/null || true
find vendor -mindepth 3 -maxdepth 3 -type d \( -name tests -o -name docs -o -name .github \) -exec rm -rf {} +
find vendor -type f \( -iname '*.md' -o -name 'phpunit.xml*' -o -name '.gitattributes' -o -name '.editorconfig' \) -delete
echo "vendor: $before → $(find vendor -type f | wc -l) Dateien"
}
build() {
say "Baue Version aus Git-Stand $(git -C "$ROOT" rev-parse --short HEAD)"
if [[ -n "$(git -C "$ROOT" status --porcelain)" ]]; then
echo "Hinweis: Nicht committete Änderungen werden NICHT ausgeliefert (gebaut wird der letzte Commit)."
fi
BUILD_DIR="$(mktemp -d)"
git -C "$ROOT" archive --format=tar HEAD | tar -x -C "$BUILD_DIR"
(
cd "$BUILD_DIR"
$COMPOSER_BIN install --no-dev --prefer-dist --optimize-autoloader --no-interaction --no-progress
npm ci --no-audit --no-fund
npm run build
rm -rf node_modules tests docs .gitea .github scripts storage .env.example .env.production.example .ai .claude .cursor AGENTS.md CLAUDE.md boost.json phpunit.xml
prune_vendor
git -C "$ROOT" rev-parse HEAD > REVISION
)
ARCHIVE="$BUILD_DIR.tgz"
tar -czf "$ARCHIVE" -C "$BUILD_DIR" .
echo "Paket: $(du -h "$ARCHIVE" | cut -f1)"
}
health_check() {
[[ -n "$DEPLOY_URL" ]] || { echo "Kein DEPLOY_URL gesetzt – Gesundheitscheck übersprungen."; return 0; }
# First deployment: the domain does not point to current/public yet.
[[ "${SKIP_HEALTH_CHECK:-}" == "1" ]] && { echo "SKIP_HEALTH_CHECK=1 – Gesundheitscheck übersprungen."; return 0; }
say "Prüfe $DEPLOY_URL/up"
for attempt in 1 2 3 4 5; do
if curl -fsS --max-time 15 "$DEPLOY_URL/up" > /dev/null; then
echo "Webseite antwortet."
return 0
fi
sleep 3
done
return 1
}
case "$COMMAND" in
setup)
say "Lege Ordnerstruktur in $DEPLOY_PATH an"
remote setup
;;
deploy)
build
RELEASE="$(date -u +%Y%m%d%H%M%S)"
say "Übertrage Version $RELEASE"
upload "$ARCHIVE" "$RELEASE"
remote receive "$RELEASE"
say "Migrieren, Caches aufwärmen, umschalten"
remote activate "$RELEASE" "$DEPLOY_KEEP"
if ! health_check; then
say "Gesundheitscheck fehlgeschlagen – schalte zurück"
remote rollback
fail "Deployment zurückgerollt. Logs: scripts/deploy.sh $ENVIRONMENT artisan about / shared/storage/logs"
fi
rm -rf "$BUILD_DIR" "$ARCHIVE"
say "Fertig: Version $RELEASE ist live."
;;
rollback)
remote rollback
health_check || fail "Auch die vorige Version antwortet nicht – bitte Logs prüfen."
;;
releases)
remote releases
;;
artisan)
remote artisan "$@"
;;
*)
fail "Unbekannter Befehl: $COMMAND (setup | deploy | rollback | releases | artisan …)"
;;
esac