#!/usr/bin/env bash
# fileshare-company-server bootstrap for Debian/Ubuntu.
#
# Adds the FileShare apt repo and signing key, then installs the
# package. Idempotent — safe to re-run; it's how customers upgrade.
#
#   curl -fsSL https://apt.filesharesystem.org/install.sh | sudo bash
#
set -euo pipefail

APT_HOST="apt.filesharesystem.org"
SUITE="stable"
COMPONENT="main"
KEY_URL="https://${APT_HOST}/filesharesystem-archive-keyring.asc"
KEYRING="/usr/share/keyrings/filesharesystem-archive-keyring.gpg"
SOURCES="/etc/apt/sources.list.d/filesharesystem.sources"

require_root() {
  if [ "$(id -u)" -ne 0 ]; then
    echo "Run as root, e.g.: curl -fsSL https://${APT_HOST}/install.sh | sudo bash" >&2
    exit 1
  fi
}

require_debian_like() {
  if [ ! -r /etc/os-release ]; then
    echo "Cannot detect OS — /etc/os-release missing." >&2
    exit 1
  fi
  # shellcheck disable=SC1091
  . /etc/os-release
  case "${ID:-} ${ID_LIKE:-}" in
    *debian*|*ubuntu*) : ;;
    *) echo "This installer supports Debian/Ubuntu. Detected: ${PRETTY_NAME:-unknown}" >&2; exit 1 ;;
  esac
}

ensure_prereqs() {
  apt-get update -qq
  apt-get install -y --no-install-recommends ca-certificates curl gnupg >/dev/null
}

install_key() {
  echo "→ fetching signing key from $KEY_URL"
  curl -fsSL "$KEY_URL" | gpg --dearmor -o "$KEYRING"
  chmod 0644 "$KEYRING"
}

install_source() {
  echo "→ writing $SOURCES"
  # deb822 format — the modern style; works on Ubuntu 22.04+ and Debian 12+.
  cat > "$SOURCES" <<EOF
Types: deb
URIs: https://${APT_HOST}
Suites: ${SUITE}
Components: ${COMPONENT}
Architectures: $(dpkg --print-architecture)
Signed-By: ${KEYRING}
EOF
  chmod 0644 "$SOURCES"
}

install_package() {
  apt-get update -qq
  apt-get install -y fileshare-company-server
}

main() {
  require_root
  require_debian_like
  ensure_prereqs
  install_key
  install_source
  install_package

  cat <<DONE

  fileshare-company-server installed.

    fileshareSRV status   — check the service
    fileshareSRV code     — fetch the first-run enrollment code
    fileshareSRV logs     — tail the server log

  Future upgrades: sudo apt update && sudo apt upgrade fileshare-company-server
DONE
}

main "$@"
