NextWks/deploy.sh

481 lines
15 KiB
Bash
Executable file

#!/usr/bin/env bash
set -euo pipefail
REPO_DIR="/opt/NextWks"
TARGET_DIR="/opt/nextworkspace"
SERVICE_NAME="nextworkspace"
BINARY_NAME="nextworkspace"
HEALTH_CHECK_RETRIES=10
HEALTH_CHECK_INTERVAL=2
# --- Load .env from runtime root ---
ENV_FILE="$TARGET_DIR/.env"
if [ -f "$ENV_FILE" ]; then
set -a
source "$ENV_FILE"
set +a
fi
# Default domain if .env wasn't loaded
DOMAIN="${DOMAIN:-nextwks.eu}"
# --- 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/6] Pulling latest code..."
git pull
echo "[2/6] Building binary and helper tool..."
export PATH=$PATH:/usr/local/go/bin
go build -o "$BINARY_NAME" .
# Build helper tool for cert management
TOOL_DIR="$REPO_DIR/tools/nextwks-tool"
TOOL_BIN="/tmp/nextwks-tool"
if [ -d "$TOOL_DIR" ]; then
cd "$TOOL_DIR"
go build -o "$TOOL_BIN" . 2>/dev/null && echo "[OK] Helper tool built" || echo "[WARN] Helper tool build failed"
cd "$REPO_DIR"
fi
# --- Certificate management via helper tool ---
if [ -f "$TOOL_BIN" ]; then
echo "[*] Managing LE certificates..."
mkdir -p /opt/backup/certs
"$TOOL_BIN" cert \
--domains "app.${DOMAIN},dns.${DOMAIN},www.${DOMAIN}" \
--email "${TLS_EMAIL:-admin@${DOMAIN}}" \
--backup-dir /opt/backup/certs 2>&1 || true
fi
# --- Greenfield path ---
if [ "$GREENFIELD" = true ]; then
echo "[3/6] Removing old deployment..."
# Unlock immutable files (chattr +i from previous deploy) before removing
if [ -d "$TARGET_DIR" ]; then
chattr -R -i "$TARGET_DIR" 2>/dev/null || true
fi
# Preserve .env and Zoraxy certs across greenfield destroy
if [ -f "$TARGET_DIR/.env" ]; then
cp "$TARGET_DIR/.env" /tmp/nextworkspace.env.bak
echo "[INFO] Preserved .env"
fi
if [ -d "$TARGET_DIR/config/zoraxy/conf/certs" ]; then
cp -r "$TARGET_DIR/config/zoraxy" /tmp/nextworkspace.zoraxy.bak
echo "[INFO] Preserved Zoraxy config + certs"
fi
rm -rf "$TARGET_DIR"
echo "[4/6] Creating target directories..."
mkdir -p "$TARGET_DIR/config/nextworkspace"
mkdir -p "$TARGET_DIR/config/zoraxy/conf/proxy"
mkdir -p "$TARGET_DIR/config/zoraxy/www/html"
mkdir -p "$TARGET_DIR/data/zoraxy"
mkdir -p "$TARGET_DIR/compose"
mkdir -p "$TARGET_DIR/logs"
# Restore preserved .env and Zoraxy config+certs
if [ -f /tmp/nextworkspace.env.bak ]; then
mv /tmp/nextworkspace.env.bak "$TARGET_DIR/.env"
chmod 600 "$TARGET_DIR/.env"
echo "[INFO] Restored .env"
fi
if [ -d /tmp/nextworkspace.zoraxy.bak ]; then
cp -r /tmp/nextworkspace.zoraxy.bak/* "$TARGET_DIR/config/zoraxy/"
rm -rf /tmp/nextworkspace.zoraxy.bak
echo "[INFO] Restored Zoraxy config + certs"
fi
echo "[5/6] Copying binary..."
cp "$BINARY_NAME" "$TARGET_DIR/$BINARY_NAME"
if [ -f "$REPO_DIR/VERSION" ]; then
cp "$REPO_DIR/VERSION" "$TARGET_DIR/VERSION"
echo "[INFO] Version: $(cat $TARGET_DIR/VERSION)"
fi
echo "[6/6] Deploying Zoraxy..."
cp compose/zoraxy.yaml "$TARGET_DIR/compose/zoraxy.yaml"
podman-compose -f "$TARGET_DIR/compose/zoraxy.yaml" up -d 2>&1 || echo "[WARN] Zoraxy deploy had issues (see above)"
# Generate Zoraxy proxy configs with full schema (prevents Zoraxy from clearing OriginIpOrDomain on expand)
echo "[*] Generating Zoraxy proxy configs..."
cat > "$TARGET_DIR/config/zoraxy/conf/proxy/app.$DOMAIN.config" <<ZORAXY_APP
{
"ProxyType": 1,
"RootOrMatchingDomain": "app.$DOMAIN",
"MatchingDomainAlias": [],
"ActiveOrigins": [
{
"OriginIpOrDomain": "127.0.0.1:9000",
"RequireTLS": false,
"SkipCertValidations": false,
"SkipWebSocketOriginCheck": false,
"Weight": 1,
"MaxConn": 0,
"RespTimeout": 0
}
],
"InactiveOrigins": [],
"UseStickySession": false,
"UseActiveLoadBalance": false,
"Disabled": false,
"BypassGlobalTLS": false,
"VirtualDirectories": [],
"HeaderRewriteRules": {
"UserDefinedHeaders": null,
"RequestHostOverwrite": "",
"HSTSMaxAge": 0,
"EnablePermissionPolicyHeader": false,
"PermissionPolicy": null,
"DisableHopByHopHeaderRemoval": false
},
"EnableWebsocketCustomHeaders": false,
"AuthenticationProvider": {
"AuthMethod": 0,
"BasicAuthCredentials": null,
"BasicAuthExceptionRules": null,
"BasicAuthGroupIDs": [],
"ForwardAuthURL": "",
"ForwardAuthResponseHeaders": [],
"ForwardAuthResponseClientHeaders": [],
"ForwardAuthRequestHeaders": [],
"ForwardAuthRequestExcludedCookies": []
},
"RequireRateLimit": false,
"RateLimit": 0,
"DisableUptimeMonitor": false,
"AccessFilterUUID": "",
"DefaultSiteOption": 0,
"DefaultSiteValue": "",
"Tags": []
}
ZORAXY_APP
cat > "$TARGET_DIR/config/zoraxy/conf/proxy/dns.$DOMAIN.config" <<ZORAXY_DNS
{
"ProxyType": 1,
"RootOrMatchingDomain": "dns.$DOMAIN",
"MatchingDomainAlias": [],
"ActiveOrigins": [
{
"OriginIpOrDomain": "127.0.0.1:8000",
"RequireTLS": false,
"SkipCertValidations": false,
"SkipWebSocketOriginCheck": false,
"Weight": 1,
"MaxConn": 0,
"RespTimeout": 0
}
],
"InactiveOrigins": [],
"UseStickySession": false,
"UseActiveLoadBalance": false,
"Disabled": false,
"BypassGlobalTLS": true,
"VirtualDirectories": [],
"HeaderRewriteRules": {
"UserDefinedHeaders": null,
"RequestHostOverwrite": "",
"HSTSMaxAge": 0,
"EnablePermissionPolicyHeader": false,
"PermissionPolicy": null,
"DisableHopByHopHeaderRemoval": false
},
"EnableWebsocketCustomHeaders": false,
"AuthenticationProvider": {
"AuthMethod": 0,
"BasicAuthCredentials": null,
"BasicAuthExceptionRules": null,
"BasicAuthGroupIDs": [],
"ForwardAuthURL": "",
"ForwardAuthResponseHeaders": [],
"ForwardAuthResponseClientHeaders": [],
"ForwardAuthRequestHeaders": [],
"ForwardAuthRequestExcludedCookies": []
},
"RequireRateLimit": false,
"RateLimit": 0,
"DisableUptimeMonitor": false,
"AccessFilterUUID": "",
"DefaultSiteOption": 0,
"DefaultSiteValue": "",
"Tags": []
}
ZORAXY_DNS
# Generate www subdomain config (proxied to binary for landing page + ACME support)
cat > "$TARGET_DIR/config/zoraxy/conf/proxy/www.$DOMAIN.config" <<ZORAXY_WWW
{
"ProxyType": 1,
"RootOrMatchingDomain": "www.$DOMAIN",
"ActiveOrigins": [{
"OriginIpOrDomain": "127.0.0.1:9000",
"RequireTLS": false,
"Weight": 1,
"MaxConn": 0
}],
"Disabled": false,
"AuthenticationProvider": {"AuthMethod": 0}
}
ZORAXY_WWW
# Copy www landing page
cp -r config/www/* "$TARGET_DIR/config/zoraxy/www/html/"
# Generate auth subdomain config (handled by Zoraxy Auth on port 5489)
echo "[*] Generating auth subdomain config..."
cat > "$TARGET_DIR/config/zoraxy/conf/proxy/auth.$DOMAIN.config" <<ZORAXY_AUTH
{
"ProxyType": 1,
"RootOrMatchingDomain": "auth.$DOMAIN",
"ActiveOrigins": [{
"OriginIpOrDomain": "127.0.0.1:5489",
"RequireTLS": false,
"Weight": 1,
"MaxConn": 0
}],
"Disabled": false,
"AuthenticationProvider": {"AuthMethod": 0}
}
ZORAXY_AUTH
# Lock proxy configs so Zoraxy cannot rewrite them (clearing OriginIpOrDomain)
echo "[*] Locking proxy configs (chattr +i)..."
chattr -R +i "$TARGET_DIR/config/zoraxy/conf/proxy/" 2>/dev/null || true
# Copy launcher config files
cp -r config/nextworkspace/* "$TARGET_DIR/config/nextworkspace/"
# Generate launcher apps.yaml with path-based URLs
echo "[*] Generating apps.yaml..."
cat > "$TARGET_DIR/config/nextworkspace/apps.yaml" <<EOF
apps:
- name: "OpenCloud"
subtitle: "File Storage"
path: "/cloud"
upstream: "http://127.0.0.1:9100"
icon: "cloud"
- name: "Euro Office"
subtitle: "Collaborative Suite"
path: "/office"
upstream: "http://127.0.0.1:9200"
icon: "office"
- name: "ERPNext"
subtitle: "Enterprise ERP"
path: "/erp"
upstream: "http://127.0.0.1:9300"
icon: "erp"
- name: "Matrix Chat"
subtitle: "Team Communication"
path: "/chat"
upstream: "http://127.0.0.1:9400"
icon: "chat"
- name: "Jitsi"
subtitle: "Video Conferencing"
path: "/meet"
upstream: "http://127.0.0.1:9500"
icon: "video"
- name: "Webmail"
subtitle: "Email Client"
path: "/mail"
upstream: "http://127.0.0.1:9600"
icon: "mail"
- name: "AI Chat"
subtitle: "Open WebUI"
path: "/ai"
upstream: "http://127.0.0.1:9700"
icon: "bot"
- name: "Portainer"
subtitle: "Container Management"
path: "/admin"
upstream: "http://127.0.0.1:9800"
icon: "admin"
EOF
# --- Configure Zoraxy admin + LE via API ---
echo "[*] Configuring Zoraxy..."
# Wait for Zoraxy to be ready
for i in $(seq 1 15); do
if curl -sf "http://127.0.0.1:8000/api/auth/userCount" > /dev/null 2>&1; then
break
fi
echo " Waiting for Zoraxy... ($i/15)"
sleep 2
done
sleep 1
# Zoraxy API helper — uses direct /login.html to avoid redirect CSRF issues
COOKIE_JAR="/tmp/zoraxy_cookies.txt"
rm -f "$COOKIE_JAR"
fetch_csrf() {
# Fetch /login.html directly (no redirect), save cookies, extract token
local page
page=$(curl -s -c "$COOKIE_JAR" -b "$COOKIE_JAR" http://127.0.0.1:8000/login.html 2>&1)
local token
token=$(echo "$page" | grep 'zoraxy.csrf.Token' | sed 's/.*content="//;s/".*//' | head -1)
echo "$token"
}
zoraxy_post() {
local path="$1" data="$2"
local csrf
csrf=$(fetch_csrf)
curl -s -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST "http://127.0.0.1:8000${path}" \
-H "X-CSRF-Token: ${csrf}" -d "${data}"
}
zoraxy_get() {
local path="$1" data="$2"
local csrf
csrf=$(fetch_csrf)
curl -s -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X GET "http://127.0.0.1:8000${path}" \
-H "X-CSRF-Token: ${csrf}" -G ${data:+-d "$data"}
}
# Step 1: Create admin account
echo " Creating admin account..."
CSRF=$(fetch_csrf)
ADMIN_RESULT=$(curl -s -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST "http://127.0.0.1:8000/api/auth/register" \
-H "X-CSRF-Token: ${CSRF}" \
-d "username=${ADMIN_USERNAME:-master}" \
-d "password=${ADMIN_PASSWORD:-9Aku7MfklZU9ldnZ}" 2>&1)
if echo "$ADMIN_RESULT" | grep -qi '"success"\|"ok"\|"registered'; then
echo " [OK] Admin account created: $ADMIN_USERNAME"
elif echo "$ADMIN_RESULT" | grep -qi 'already\|exist'; then
echo " [OK] Admin account already exists"
else
echo " [INFO] Admin registration: $ADMIN_RESULT"
fi
# Step 2: Login (saves session cookie in $COOKIE_JAR)
echo " Logging in for LE configuration..."
CSRF=$(fetch_csrf)
LOGIN_RESULT=$(curl -s -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST "http://127.0.0.1:8000/api/auth/login" \
-H "X-CSRF-Token: ${CSRF}" \
-d "username=${ADMIN_USERNAME:-master}" \
-d "password=${ADMIN_PASSWORD:-9Aku7MfklZU9ldnZ}" 2>&1)
if echo "$LOGIN_RESULT" | grep -qi '"success"\|"ok"'; then
echo " [OK] Logged in as $ADMIN_USERNAME"
# Set LE email
echo " Setting Let's Encrypt email: ${TLS_EMAIL}"
zoraxy_post "/api/acme/autoRenew/email" "set=${TLS_EMAIL}" > /dev/null
# Obtain certificates for all subdomains
LE_CA="Let%27s%20Encrypt"
for SUB in app dns www; do
echo " Requesting LE certificate for ${SUB}.${DOMAIN}..."
CERT_RESULT=$(curl -s --max-time 60 -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X GET "http://127.0.0.1:8000/api/acme/obtainCert" \
-H "X-CSRF-Token: $(fetch_csrf)" \
-G -d "domains=${SUB}.${DOMAIN}" -d "filename=${SUB}.${DOMAIN}" \
-d "email=${TLS_EMAIL}" -d "ca=${LE_CA}" -d "dns=false" 2>&1)
if echo "$CERT_RESULT" | grep -qi '"success"\|"ok"\|"installed\|true'; then
echo " [OK] Certificate obtained for ${SUB}.${DOMAIN}"
else
echo " [INFO] ${SUB}.${DOMAIN}: $CERT_RESULT (expected if DNS doesn't resolve)"
fi
done
# Enable auto-renew
echo " Enabling auto-renew..."
zoraxy_post "/api/acme/autoRenew/enable" "enable=true" > /dev/null
echo " [OK] LE auto-renew enabled"
# Configure Zoraxy Auth gateway in BoltDB
echo " Configuring Zoraxy Auth gateway..."
SYS_DB="$TARGET_DIR/data/zoraxy/sys.db"
if [ -f "$SYS_DB" ] && [ -f "$TOOL_BIN" ]; then
"$TOOL_BIN" db \
--db "$SYS_DB" \
--set "zorxauth:options:{\"enable_auth_gateway\":true,\"sso_redirect_url\":\"https://app.${DOMAIN}/\"}" 2>&1 || true
echo " [OK] Zoraxy Auth gateway configured"
fi
else
echo " [WARN] Login failed: $LOGIN_RESULT"
fi
# Restart Zoraxy to pick up configs
echo "[*] Restarting Zoraxy to apply configs..."
podman-compose -f "$TARGET_DIR/compose/zoraxy.yaml" restart 2>&1 || true
sleep 2
# Write systemd service with EnvironmentFile for .env vars
echo "[*] Writing systemd service..."
cat > /etc/systemd/system/$SERVICE_NAME.service <<UNIT
[Unit]
Description=NextWorkspace Launcher + Auth Proxy
After=network.target
[Service]
Environment=CONFIG_DIR=$TARGET_DIR/config/nextworkspace
EnvironmentFile=$TARGET_DIR/.env
ExecStart=$TARGET_DIR/$BINARY_NAME
WorkingDirectory=$TARGET_DIR
Restart=always
User=root
Group=root
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now $SERVICE_NAME
# --- Smart update path ---
else
echo "[3/6] Stopping launcher..."
systemctl stop $SERVICE_NAME 2>/dev/null || true
echo "[4/6] Swapping binary..."
cp "$BINARY_NAME" "$TARGET_DIR/$BINARY_NAME"
echo "[5/6] Refreshing configs..."
if [ -f config/nextworkspace/apps.yaml ]; then
cp config/nextworkspace/apps.yaml "$TARGET_DIR/config/nextworkspace/apps.yaml"
fi
if [ -d config/zoraxy/conf/proxy ]; then
# Unlock, copy, re-lock to prevent Zoraxy from clearing OriginIpOrDomain
chattr -R -i "$TARGET_DIR/config/zoraxy/conf/proxy/" 2>/dev/null || true
cp config/zoraxy/conf/proxy/* "$TARGET_DIR/config/zoraxy/conf/proxy/" 2>/dev/null || true
chattr -R +i "$TARGET_DIR/config/zoraxy/conf/proxy/" 2>/dev/null || true
fi
echo "[6/6] Restarting Zoraxy and launcher..."
podman-compose -f "$TARGET_DIR/compose/zoraxy.yaml" restart 2>&1 || true
systemctl restart $SERVICE_NAME
fi
# --- Health check ---
echo "[*] Running health check..."
for i in $(seq 1 $HEALTH_CHECK_RETRIES); do
if curl -sf http://127.0.0.1:9000/health > /dev/null 2>&1; then
echo "[OK] NextWorkspace launcher is healthy on http://127.0.0.1:9000/"
exit 0
fi
echo " Attempt $i/$HEALTH_CHECK_RETRIES — not ready yet..."
sleep $HEALTH_CHECK_INTERVAL
done
echo "[FAIL] Health check failed — launcher did not respond on port 9000"
exit 1