#!/usr/bin/env bash
#
# setup_peekaping.sh
# Installs Docker (if missing) and deploys Peekaping (self-hosted uptime monitor)
# using the official monolithic SQLite bundle image.
#
# Usage:
#   sudo bash setup_peekaping.sh
#
set -euo pipefail

# ------------------------------------------------------------------
# Configurable options
# ------------------------------------------------------------------
PEEKAPING_PORT="8383"                     # Host port to expose the web UI/API on
PEEKAPING_DIR="/opt/peekaping"            # Where data will be persisted on the host
CONTAINER_NAME="peekaping"
IMAGE="0xfurai/peekaping-bundle-sqlite:latest"
OPEN_FIREWALL="true"                      # Set to "false" to skip ufw rule

# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
log() { echo -e "\n\033[1;32m[+] $*\033[0m"; }
err() { echo -e "\n\033[1;31m[!] $*\033[0m" >&2; }

if [[ $EUID -ne 0 ]]; then
  err "Please run this script as root (e.g. with sudo)."
  exit 1
fi

# ------------------------------------------------------------------
# 1. Make sure basic prerequisites (curl, ca-certificates) are present
# ------------------------------------------------------------------
if ! command -v curl &>/dev/null; then
  log "curl not found. Installing prerequisites..."
  if command -v apt-get &>/dev/null; then
    apt-get update -y
    apt-get install -y curl ca-certificates
  elif command -v dnf &>/dev/null; then
    dnf install -y curl ca-certificates
  elif command -v yum &>/dev/null; then
    yum install -y curl ca-certificates
  else
    err "Could not detect a supported package manager (apt/dnf/yum) to install curl. Please install curl manually and re-run."
    exit 1
  fi
fi

# ------------------------------------------------------------------
# 2. Install Docker if it's not already present
# ------------------------------------------------------------------
if ! command -v docker &>/dev/null; then
  log "Docker not found. Installing Docker..."
  curl -fsSL https://get.docker.com | sh
  systemctl enable --now docker
else
  log "Docker already installed: $(docker --version)"
fi

# Make sure docker is running
systemctl enable --now docker >/dev/null 2>&1 || true

# ------------------------------------------------------------------
# 3. Create data directory for persistence
# ------------------------------------------------------------------
log "Creating data directory at ${PEEKAPING_DIR}/.data/sqlite"
mkdir -p "${PEEKAPING_DIR}/.data/sqlite"

# ------------------------------------------------------------------
# 4. Pull the latest Peekaping image
# ------------------------------------------------------------------
log "Pulling Peekaping image (${IMAGE})..."
docker pull "${IMAGE}"

# ------------------------------------------------------------------
# 5. Remove any existing container with the same name (idempotent re-run)
# ------------------------------------------------------------------
if docker ps -a --format '{{.Names}}' | grep -qx "${CONTAINER_NAME}"; then
  log "Existing container named '${CONTAINER_NAME}' found. Removing it..."
  docker rm -f "${CONTAINER_NAME}"
fi

# ------------------------------------------------------------------
# 6. Run the Peekaping container
# ------------------------------------------------------------------
log "Starting Peekaping container on port ${PEEKAPING_PORT}..."
docker run -d \
  --name "${CONTAINER_NAME}" \
  --restart=always \
  -p "${PEEKAPING_PORT}:8383" \
  -e DB_NAME=/app/data/peekaping.db \
  -v "${PEEKAPING_DIR}/.data/sqlite:/app/data" \
  "${IMAGE}"

# ------------------------------------------------------------------
# 7. Open the firewall port (ufw), if enabled and ufw is present
# ------------------------------------------------------------------
if [[ "${OPEN_FIREWALL}" == "true" ]] && command -v ufw &>/dev/null; then
  log "Opening port ${PEEKAPING_PORT} in ufw..."
  ufw allow "${PEEKAPING_PORT}/tcp" || true
fi

# ------------------------------------------------------------------
# 8. Verify container is running
# ------------------------------------------------------------------
sleep 3
if docker ps --format '{{.Names}}' | grep -qx "${CONTAINER_NAME}"; then
  SERVER_IP=$(curl -fsSL ifconfig.me || hostname -I | awk '{print $1}')
  log "Peekaping is up and running!"
  echo -e "\n  Access it at:  http://${SERVER_IP}:${PEEKAPING_PORT}\n"
  echo "  Data persisted at: ${PEEKAPING_DIR}/.data/sqlite"
  echo "  Container name:    ${CONTAINER_NAME}"
  echo ""
  echo "  Useful commands:"
  echo "    docker logs -f ${CONTAINER_NAME}     # view logs"
  echo "    docker restart ${CONTAINER_NAME}     # restart"
  echo "    docker stop ${CONTAINER_NAME}        # stop"
else
  err "Container did not start correctly. Check logs with: docker logs ${CONTAINER_NAME}"
  exit 1
fi
