#!/usr/bin/env bash # Provision (or verify) the server-side .env / APP_KEY on the xamxam host. # # Behavior: # - If remote /var/www/xamxam/.env already contains APP_KEY=... → DO NOT # overwrite it. Print a clear message and exit 0. # - If the file exists but has no APP_KEY → append a fresh key. # - If the file does not exist → create it with a fresh key. # Always fixes ownership (www-data:xamxam) and perms (640) after any write. # # Run from local via: just provision-server # (uses the `xamxam` SSH host as defined in ~/.ssh/config / deploy recipes) set -euo pipefail HOST="${1:-xamxam}" ENV_PATH="/var/www/xamxam/.env" GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; RED='\033[0;31m'; NC='\033[0m' ok() { printf "${GREEN}✓${NC} %s\n" "$*"; } warn() { printf "${YELLOW}!${NC} %s\n" "$*"; } info() { printf "${CYAN}→${NC} %s\n" "$*"; } die() { printf "${RED}✗${NC} %s\n" "$*" >&2; exit 1; } info "Checking ${ENV_PATH} on ${HOST}…" # Does the file exist AND already have an APP_KEY value? if ssh "$HOST" "test -f '$ENV_PATH' && grep -qE '^\s*APP_KEY=\S+' '$ENV_PATH'"; then ok "APP_KEY already present in ${ENV_PATH} on ${HOST} — NOT overwriting it." warn "Keeping the existing key so encrypted credentials stay decryptable." warn "If you intend to rotate the key, use: just reencrypt-password " exit 0 fi info "APP_KEY absent — generating one on the server…" # Build the new key value once, server-side. if ssh "$HOST" "command -v php >/dev/null 2>&1"; then KEY="$(ssh "$HOST" "php -r 'echo base64_encode(random_bytes(32));'")" else die "php not found on ${HOST} — cannot generate APP_KEY remotely." fi # Append or create, always via root (app dir is not writable by www-data). if ssh "$HOST" "test -f '$ENV_PATH'"; then warn "${ENV_PATH} exists but has no APP_KEY — appending (existing lines untouched)." ssh "$HOST" "{ printf '\nAPP_KEY=%s\n' '$KEY'; } | sudo tee -a '$ENV_PATH' >/dev/null" ok "APP_KEY appended to ${ENV_PATH}." else ssh "$HOST" "echo 'APP_KEY=${KEY}' | sudo tee '$ENV_PATH' >/dev/null" info "Created ${ENV_PATH} with a new APP_KEY." fi # Normalise ownership + perms regardless of which branch wrote. ssh "$HOST" "sudo chown www-data:xamxam '$ENV_PATH' && sudo chmod 640 '$ENV_PATH'" ok "Ownership www-data:xamxam, permissions 640." ok "Server APP_KEY ready."