#!/usr/bin/env bash
#
#  Mattermost Team Edition — one-shot installer for Fedora 44
#  From the NUILab docs: https://help.nuilab.org/systems/mattermost/self-hosting/
#
#  ⚠️  USE AT YOUR OWN RISK.  Provided as-is, with NO warranty of any kind.
#      NUILab does not guarantee this script works or is current. Read it before
#      you run it, and run it only on a server YOU own and can afford to wipe.
#
#  What it does: installs Docker, opens firewalld (80/443), writes the stack
#  files into /opt/mattermost, and starts Postgres + Mattermost + Caddy (TLS).
#  Note the SELinux ":ro,Z" relabel on the Caddyfile mount — required on Fedora.
#
#  Usage:   sudo bash mattermost-install-fedora44.sh chat.example.edu
#  (You must already have a DNS A record for that domain pointing at this server,
#   and ports 80 + 443 reachable from the internet — including any cloud firewall.)
#
set -euo pipefail

# ---- preconditions ---------------------------------------------------------
if [ "$(id -u)" -ne 0 ]; then
  echo "Please run with sudo:  sudo bash $0 <your-domain>" >&2
  exit 1
fi
if ! grep -qi 'fedora' /etc/os-release; then
  echo "This script targets Fedora 44. Your /etc/os-release is not Fedora." >&2
  echo "Use the Ubuntu or AlmaLinux script instead, or run the manual steps." >&2
  exit 1
fi

DOMAIN="${1:-}"
if [ -z "$DOMAIN" ]; then
  read -rp "Domain for this server (e.g. chat.example.edu): " DOMAIN
fi
if [ -z "$DOMAIN" ]; then echo "No domain given. Aborting." >&2; exit 1; fi

INSTALL_DIR=/opt/mattermost
MM_VERSION=11.7   # pin a version; check Docker Hub for the current Team Edition tag

echo "==> Installing Mattermost for https://${DOMAIN} into ${INSTALL_DIR}"

# ---- 1. Docker Engine + Compose plugin (Docker's official dnf repo) --------
echo "==> [1/4] Installing Docker"
dnf -y install dnf-plugins-core
# dnf5 (Fedora 44) syntax:
dnf config-manager addrepo --from-repofile=https://download.docker.com/linux/fedora/docker-ce.repo
if ! dnf install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin; then
  echo "    docker-ce not available (Docker may not ship Fedora 44 packages yet)."
  echo "    Falling back to Fedora's own engine (moby-engine)."
  dnf install -y moby-engine docker-compose-plugin
fi
systemctl enable --now docker
if [ -n "${SUDO_USER:-}" ] && [ "${SUDO_USER}" != "root" ]; then
  usermod -aG docker "${SUDO_USER}" || true
fi

# ---- 2. Firewall: firewalld is on by default; allow http/https -------------
echo "==> [2/4] Configuring firewalld"
if command -v firewall-cmd >/dev/null 2>&1 && systemctl is-active --quiet firewalld; then
  firewall-cmd --permanent --add-service=http
  firewall-cmd --permanent --add-service=https
  firewall-cmd --reload
else
  echo "    firewalld not active; skipping (open 80/443 yourself if you firewall elsewhere)."
fi

# ---- 3. Stack files --------------------------------------------------------
echo "==> [3/4] Writing stack files to ${INSTALL_DIR}"
mkdir -p "${INSTALL_DIR}"
cd "${INSTALL_DIR}"

if [ ! -f .env ]; then
  PWGEN="$(openssl rand -hex 24)"
  cat > .env <<EOF
POSTGRES_PASSWORD=${PWGEN}
DOMAIN=${DOMAIN}
EOF
  chmod 600 .env
  echo "    wrote .env (DB password generated; keep this file private)"
else
  echo "    .env already exists — leaving it untouched"
fi

# NOTE the Caddyfile mount: ":ro,Z" — SELinux relabel so the container can read it.
cat > docker-compose.yml <<'YAML'
services:
  postgres:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_USER: mmuser
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: mattermost
    volumes:
      - postgres-data:/var/lib/postgresql/data
    networks:
      - backend
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U mmuser -d mattermost"]
      interval: 10s
      timeout: 5s
      retries: 5

  mattermost:
    image: mattermost/mattermost-team-edition:MM_VERSION_PLACEHOLDER
    restart: unless-stopped
    depends_on:
      postgres:
        condition: service_healthy
    environment:
      MM_SQLSETTINGS_DRIVERNAME: postgres
      MM_SQLSETTINGS_DATASOURCE: "postgres://mmuser:${POSTGRES_PASSWORD}@postgres:5432/mattermost?sslmode=disable&connect_timeout=10"
      MM_SERVICESETTINGS_SITEURL: https://${DOMAIN}
      MM_SERVICESETTINGS_ENABLELOCALMODE: "true"
    volumes:
      - mattermost-data:/mattermost/data
      - mattermost-config:/mattermost/config
      - mattermost-logs:/mattermost/logs
      - mattermost-plugins:/mattermost/plugins
      - mattermost-client-plugins:/mattermost/client/plugins
      - mattermost-bleve:/mattermost/bleve-indexes
    networks:
      - backend
      - frontend

  caddy:
    image: caddy:2-alpine
    restart: unless-stopped
    depends_on:
      - mattermost
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro,Z
      - caddy-data:/data
      - caddy-config:/config
    networks:
      - frontend

networks:
  backend:
  frontend:

volumes:
  postgres-data:
  mattermost-data:
  mattermost-config:
  mattermost-logs:
  mattermost-plugins:
  mattermost-client-plugins:
  mattermost-bleve:
  caddy-data:
  caddy-config:
YAML
sed -i "s/MM_VERSION_PLACEHOLDER/${MM_VERSION}/" docker-compose.yml

cat > Caddyfile <<EOF
${DOMAIN} {
    reverse_proxy mattermost:8065
}
EOF

# ---- 4. Launch -------------------------------------------------------------
echo "==> [4/4] Starting the stack"
docker compose up -d
echo
echo "Done. Watch it come up with:   cd ${INSTALL_DIR} && docker compose logs -f"
echo "Then open:   https://${DOMAIN}"
echo "The FIRST account you create becomes the system administrator."
echo
echo "Reminder: this is provided AS-IS with no warranty. You own this server now."
