#!/usr/bin/env bash
#
# Espresso Cloud — Bring Your Own Cloud (BYOC) server setup
# Guide: https://espresso.zimplify.tech/guide/espresso/byoc
#
# Run this once on a fresh Ubuntu server, as root (via sudo). It performs the
# entire server-side setup that Espresso needs — and nothing else:
#
#   1. Installs Docker Engine using Docker's official installer
#      (curl -fsSL https://get.docker.com -o get-docker.sh && sh get-docker.sh).
#   2. Creates a dedicated, password-less Linux user named "espresso".
#   3. Adds "espresso" to the "docker" group so Espresso can build and run
#      containers — including ones that bind to ports 80 and 443. (The Docker
#      daemon runs as root and binds those privileged ports on the user's
#      behalf, so docker-group membership is all that's required.)
#   4. Authorizes Espresso's public SSH key for the "espresso" user so the
#      platform can connect over SSH to deploy and manage your workloads.
#   5. Creates /opt/espresso (where Espresso stores all its files and sites)
#      and gives the "espresso" user full ownership of it and its contents,
#      so Espresso can manage that directory without root.
#
# It does NOT open firewall ports, install ERPNext, or touch any of your other
# applications or users. You are encouraged to read every line before running.
#
# Usage:
#   curl -fsSL https://espresso.zimplify.tech/byoc-setup.sh -o espresso-byoc-setup.sh
#   sudo bash espresso-byoc-setup.sh
#
set -euo pipefail

# The dedicated user Espresso connects as.
ESPRESSO_USER="espresso"

# Espresso's public SSH key. The matching private key never leaves Espresso's
# infrastructure. You can revoke access any time by removing this line from
# /home/espresso/.ssh/authorized_keys.
ESPRESSO_PUBKEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC1/s/7dvopaVxaQRUh9n36fcB0OggEmzGDeeQa7J4E4 cloud@tacten.co"

# --- 0. Require root ---------------------------------------------------------
if [ "$(id -u)" -ne 0 ]; then
  echo "ERROR: this script must run as root. Re-run it with:" >&2
  echo "  sudo bash $0" >&2
  exit 1
fi

# --- 1. Install Docker Engine ------------------------------------------------
echo "==> [1/5] Installing Docker Engine ..."
if command -v docker >/dev/null 2>&1; then
  echo "    Docker is already installed — skipping."
else
  curl -fsSL https://get.docker.com -o get-docker.sh
  sh get-docker.sh
  rm -f get-docker.sh
fi

# Make sure the Docker daemon is enabled and running (no-op if already so).
if command -v systemctl >/dev/null 2>&1; then
  systemctl enable --now docker
fi

# --- 2. Create the espresso user ---------------------------------------------
echo "==> [2/5] Creating the '${ESPRESSO_USER}' user ..."
if id "${ESPRESSO_USER}" >/dev/null 2>&1; then
  echo "    User '${ESPRESSO_USER}' already exists — skipping."
else
  # --disabled-password: no password login is ever possible — SSH key only.
  adduser --disabled-password --gecos "" "${ESPRESSO_USER}"
fi

# --- 3. Grant Docker access --------------------------------------------------
echo "==> [3/5] Adding '${ESPRESSO_USER}' to the 'docker' group ..."
usermod -aG docker "${ESPRESSO_USER}"

# --- 4. Authorize Espresso's SSH key -----------------------------------------
echo "==> [4/5] Authorizing Espresso's public SSH key ..."
ESPRESSO_HOME="$(getent passwd "${ESPRESSO_USER}" | cut -d: -f6)"
AUTH_KEYS="${ESPRESSO_HOME}/.ssh/authorized_keys"

# ~/.ssh must be 700 and authorized_keys 600, both owned by the user, or SSH
# will refuse the key.
install -d -m 700 -o "${ESPRESSO_USER}" -g "${ESPRESSO_USER}" "${ESPRESSO_HOME}/.ssh"
touch "${AUTH_KEYS}"
if ! grep -qF "${ESPRESSO_PUBKEY}" "${AUTH_KEYS}"; then
  echo "${ESPRESSO_PUBKEY}" >> "${AUTH_KEYS}"
  echo "    Key added."
else
  echo "    Key already authorized — skipping."
fi
chmod 600 "${AUTH_KEYS}"
chown "${ESPRESSO_USER}:${ESPRESSO_USER}" "${AUTH_KEYS}"

# --- 5. Create Espresso's data directory -------------------------------------
echo "==> [5/5] Creating /opt/espresso and granting '${ESPRESSO_USER}' ownership ..."
# /opt is root-owned, so create the directory as root, then hand the whole tree
# (directory + any existing contents) to the espresso user. After this Espresso
# can read/write everything under /opt/espresso without root.
ESPRESSO_DIR="/opt/espresso"
install -d -o "${ESPRESSO_USER}" -g "${ESPRESSO_USER}" "${ESPRESSO_DIR}"
chown -R "${ESPRESSO_USER}:${ESPRESSO_USER}" "${ESPRESSO_DIR}"
chmod -R u+rwX "${ESPRESSO_DIR}"

# --- Done --------------------------------------------------------------------
cat <<'EOF'

✅ Server setup complete.

   The "espresso" user is ready, has Docker access, Espresso's key is
   authorized, and /opt/espresso is owned by the "espresso" user.

   Next steps:
     1. Make sure your firewall allows inbound port 22 from 91.99.127.193/32
        (Espresso), plus ports 80 and 443 for your sites.
     2. In your Espresso dashboard, add this server by its public IP address
        and click "Test connection".

   Full guide: https://espresso.zimplify.tech/guide/espresso/byoc
EOF
