NextWks/deploy.sh

97 lines
2.5 KiB
Bash
Executable file

#!/usr/bin/env bash
set -euo pipefail
REPO_DIR="/opt/NextWks"
TARGET_DIR="/opt/workspace"
SERVICE_NAME="nextworkspace"
BINARY_NAME="nextworkspace"
HEALTH_CHECK_RETRIES=10
HEALTH_CHECK_INTERVAL=2
# --- Mode detection ---
GREENFIELD=false
if [ "${1:-}" = "--destroy" ]; then
GREENFIELD=true
echo "[MODE] Greenfield deploy (--destroy)"
elif [ ! -d "$TARGET_DIR" ]; then
GREENFIELD=true
echo "[MODE] Greenfield deploy (target missing)"
else
echo "[MODE] Smart update (target exists)"
fi
# --- Common: pull + build ---
cd "$REPO_DIR"
echo "[1/8] Pulling latest code..."
git pull
echo "[2/8] Building binary..."
export PATH=$PATH:/usr/local/go/bin
go build -o "$BINARY_NAME" .
# --- Greenfield path ---
if [ "$GREENFIELD" = true ]; then
echo "[3/8] Removing old deployment..."
rm -rf "$TARGET_DIR"
echo "[4/8] Creating target directories..."
mkdir -p "$TARGET_DIR/configs/core/certs"
echo "[5/8] Copying binary..."
cp "$BINARY_NAME" "$TARGET_DIR/$BINARY_NAME"
echo "[6/8] Copying config files..."
cp configs/core/config.yaml "$TARGET_DIR/configs/core/config.yaml"
cp configs/core/proxies.yaml "$TARGET_DIR/configs/core/proxies.yaml"
echo "[7/8] Writing systemd service..."
cat > /etc/systemd/system/$SERVICE_NAME.service <<UNIT
[Unit]
Description=NextWorkspace
After=network.target
[Service]
Environment=CONFIG_DIR=$TARGET_DIR/configs/core
ExecStart=$TARGET_DIR/$BINARY_NAME
WorkingDirectory=$TARGET_DIR
Restart=always
User=root
Group=root
[Install]
WantedBy=multi-user.target
UNIT
echo "[8/8] Starting service..."
systemctl daemon-reload
systemctl enable --now $SERVICE_NAME
# --- Smart update path ---
else
echo "[3/8] Stopping service..."
systemctl stop $SERVICE_NAME
echo "[4/8] Swapping binary..."
cp "$BINARY_NAME" "$TARGET_DIR/$BINARY_NAME"
echo "[5/8] Refreshing configs..."
cp configs/core/config.yaml "$TARGET_DIR/configs/core/config.yaml"
cp configs/core/proxies.yaml "$TARGET_DIR/configs/core/proxies.yaml"
echo "[6/8] Restarting service..."
systemctl restart $SERVICE_NAME
fi
# --- Health check (both modes) ---
echo "[*] Running health check..."
for i in $(seq 1 $HEALTH_CHECK_RETRIES); do
if curl -sf http://localhost:80/ > /dev/null 2>&1; then
echo "[OK] NextWorkspace is serving on http://localhost:80/"
exit 0
fi
echo " Attempt $i/$HEALTH_CHECK_RETRIES — not ready yet..."
sleep $HEALTH_CHECK_INTERVAL
done
echo "[FAIL] Health check failed — service did not respond on port 80"
exit 1