#!/bin/bash

# Single entry point for deployment/update.
# Default: regular update
# --init : first-time setup (service installation)

set -euo pipefail

MODE="${1:-update}"
REPO_DIR="/home/torsten/singlechat"
TARGET_DIR="/opt/ypchat"
SERVICE_NAME="ypchat"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
APP_USER="www-data"

echo "=========================================="
echo "SingleChat Update"
echo "Mode: ${MODE}"
echo "=========================================="

cd "$REPO_DIR"
git fetch --all --prune
git pull

echo "Deploy nach ${TARGET_DIR}..."
sudo "$REPO_DIR/deploy-to-opt.sh"

if [[ "$MODE" == "--init" || "$MODE" == "init" ]]; then
  echo "Initiales Setup: Service wird installiert..."
  sudo "$REPO_DIR/install-service-ypchat.sh"
elif [[ ! -f "$SERVICE_FILE" ]]; then
  echo "Service-Datei nicht gefunden, installiere Service einmalig..."
  sudo "$REPO_DIR/install-service-ypchat.sh"
fi

echo "Installiere/aktualisiere App-Abhängigkeiten und baue Client..."
sudo -u "$APP_USER" bash -c "cd '$TARGET_DIR' && ./install.sh"

echo "Starte Service neu..."
sudo systemctl restart "$SERVICE_NAME"
sudo systemctl status "$SERVICE_NAME" --no-pager -l

echo ""
echo "✓ Update erfolgreich abgeschlossen."
