#!/usr/bin/env bash
set -euo pipefail

BASE_URL="${BASE_URL:-https://wivid.web.upirate.se}"
RELEASE_TAR="${RELEASE_TAR:-releases/prod/latest.tar.gz}"
RELEASE_SHA="${RELEASE_SHA:-releases/prod/latest.sha256}"
INSTALL_DIR="${INSTALL_DIR:-/opt/wivid}"
SERVER_IP="${1:-${SERVER_IP:-}}"

log() {
  printf '[wivid-installer] %s\n' "$*"
}

download_file() {
  local url="$1"
  local out="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$url" -o "$out"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$out" "$url"
  else
    echo "Need curl or wget" >&2
    exit 1
  fi
}

install_docker_if_missing() {
  if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
    log "Docker already installed"
    return
  fi

  if ! command -v apt-get >/dev/null 2>&1; then
    echo "Unsupported package manager. Install Docker manually and rerun." >&2
    exit 1
  fi

  log "Installing Docker"
  sudo apt-get update -qq
  sudo apt-get install -y -qq ca-certificates curl gnupg lsb-release
  sudo install -m 0755 -d /etc/apt/keyrings
  curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /tmp/docker.asc
  sudo cp /tmp/docker.asc /etc/apt/keyrings/docker.asc
  sudo chmod a+r /etc/apt/keyrings/docker.asc
  echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo \"$VERSION_CODENAME\") stable" | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null
  sudo apt-get update -qq
  sudo apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  sudo systemctl enable docker >/dev/null 2>&1 || true
  sudo systemctl start docker >/dev/null 2>&1 || true
  sudo usermod -aG docker "$USER" || true
}

main() {
  command -v sha256sum >/dev/null 2>&1 || {
    echo "sha256sum missing" >&2
    exit 1
  }

  install_docker_if_missing

  tmp="$(mktemp -d)"
  trap 'rm -rf "$tmp"' EXIT

  log "Downloading release files"
  download_file "$BASE_URL/$RELEASE_SHA" "$tmp/release.sha256"
  download_file "$BASE_URL/$RELEASE_TAR" "$tmp/release.tar.gz"

  log "Verifying checksum"
  (cd "$tmp" && sha256sum -c release.sha256)

  sudo mkdir -p "$INSTALL_DIR"
  sudo tar -xzf "$tmp/release.tar.gz" -C "$INSTALL_DIR"

  if [[ -z "$SERVER_IP" ]]; then
    SERVER_IP="$(hostname -I | awk '{print $1}')"
  fi

  echo "SERVER_IP=$SERVER_IP" | sudo tee "$INSTALL_DIR/.env" >/dev/null

  log "Starting services"
  sudo docker compose -f "$INSTALL_DIR/docker-compose.yml" --env-file "$INSTALL_DIR/.env" up -d --build

  log "Deploy complete"
  log "Frontend: http://$SERVER_IP"
  log "Backend:  http://$SERVER_IP:5001"
  log "Modbus:   http://$SERVER_IP:5005"
  log "Sensor:   http://$SERVER_IP:5006"
}

main "$@"
