#!/usr/bin/env bash
# =============================================================================
# Carbacan Dev Environment Setup
# Ubuntu 24.04 LTS — Einmalig nach Erst-Installation ausführen
# Aufruf: curl -fsSL https://setup.carbacan.dev/setup/vm-setup.sh | bash
# =============================================================================
set -e

GITLAB_URL="https://gitlab.carbacan.dev"
ROCKETCHAT_URL="https://chat.carbacan.dev"
NEXTCLOUD_URL="https://nextcloud.carbacan.dev"
MCP_URL="https://mcp.carbacan.dev/sse"
CLAUDE_CONFIG_DIR="$HOME/.claude"

# Architektur erkennen (amd64 oder arm64 für Apple Silicon / Parallels)
ARCH=$(dpkg --print-architecture)

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'
step() { echo -e "\n${BLUE}▶ $1${NC}"; }
ok()   { echo -e "  ${GREEN}✓ $1${NC}"; }
warn() { echo -e "  ${YELLOW}⚠ $1${NC}"; }

echo -e "${GREEN}"
echo "  ╔══════════════════════════════════════════════╗"
echo "  ║   Carbacan Dev Environment Setup v1.4        ║"
echo "  ║   Ubuntu 24.04 LTS (Arch: $ARCH)             ║"
echo "  ╚══════════════════════════════════════════════╝"
echo -e "${NC}"

# ── 0. Benutzerdaten abfragen (via /dev/tty für curl|bash Kompatibilität) ──
TTY_IN=/dev/tty

GIT_NAME=""
GIT_EMAIL=""
GITLAB_USER=""

while [ -z "$GIT_NAME" ]; do
  printf "Dein Name (für Git-Commits, z.B. Max Mustermann): " > /dev/tty
  read -r GIT_NAME < "$TTY_IN"
done

while [ -z "$GIT_EMAIL" ]; do
  printf "Deine E-Mail (gleiche wie in GitLab): " > /dev/tty
  read -r GIT_EMAIL < "$TTY_IN"
done

while [ -z "$GITLAB_USER" ]; do
  printf "Dein GitLab-Username: " > /dev/tty
  read -r GITLAB_USER < "$TTY_IN"
done

echo ""
echo -e "  ${GREEN}Konfiguration:${NC} $GIT_NAME <$GIT_EMAIL> / @$GITLAB_USER  [Arch: $ARCH]"
echo ""

# ── 1. System aktualisieren ────────────────────────────────────────────────
step "1/11 System aktualisieren"
sudo dpkg --configure -a 2>/dev/null || true
sudo apt-get install -f -y -qq 2>/dev/null || true
sudo apt-get update -qq && sudo apt-get upgrade -y -qq
sudo apt-get install -y -qq \
  curl wget git unzip zip jq \
  apt-transport-https ca-certificates gnupg lsb-release \
  software-properties-common build-essential
ok "Basispakete installiert"

# ── 2. Git konfigurieren ───────────────────────────────────────────────────
step "2/11 Git konfigurieren"
git config --global user.name  "$GIT_NAME"
git config --global user.email "$GIT_EMAIL"
git config --global init.defaultBranch main
git config --global core.editor "code --wait" 2>/dev/null || true
ok "Git konfiguriert ($GIT_NAME <$GIT_EMAIL>)"

# ── 3. SSH-Key für GitLab ──────────────────────────────────────────────────
step "3/11 SSH-Key generieren"
SSH_KEY="$HOME/.ssh/id_ed25519_carbacan"
if [ ! -f "$SSH_KEY" ]; then
  mkdir -p "$HOME/.ssh" && chmod 700 "$HOME/.ssh"
  ssh-keygen -t ed25519 -C "${GIT_EMAIL}" -f "$SSH_KEY" -N ""
  ok "SSH-Key erstellt: $SSH_KEY"
else
  warn "SSH-Key existiert bereits: $SSH_KEY"
fi

# SSH-Config für GitLab
SSH_CONFIG="$HOME/.ssh/config"
if ! grep -q "gitlab.carbacan.dev" "$SSH_CONFIG" 2>/dev/null; then
  cat >> "$SSH_CONFIG" << SSHEOF

Host gitlab.carbacan.dev
    HostName gitlab.carbacan.dev
    Port 2222
    User git
    IdentityFile $SSH_KEY
    StrictHostKeyChecking no
SSHEOF
  chmod 600 "$SSH_CONFIG"
fi

show_ssh_key_instructions() {
  echo "" > /dev/tty
  echo -e "${YELLOW}══════════════════════════════════════════════════════${NC}" > /dev/tty
  echo -e "${YELLOW}  SSH Public Key — in GitLab eintragen:${NC}" > /dev/tty
  echo -e "${YELLOW}  1. Browser öffnen: $GITLAB_URL/-/profile/keys${NC}" > /dev/tty
  echo -e "${YELLOW}  2. Unten stehenden Key kopieren und einfügen${NC}" > /dev/tty
  echo -e "${YELLOW}  3. Titel vergeben (z.B. 'VM $GITLAB_USER'), speichern${NC}" > /dev/tty
  echo "" > /dev/tty
  cat "${SSH_KEY}.pub"
  echo "" > /dev/tty
  echo -e "${YELLOW}══════════════════════════════════════════════════════${NC}" > /dev/tty
}

show_ssh_key_instructions
printf "  Drücke ENTER wenn der Key in GitLab hinterlegt ist..." > /dev/tty
read -r _DUMMY < "$TTY_IN"

# ── 4. Docker installieren ─────────────────────────────────────────────────
step "4/11 Docker installieren"
if ! command -v docker &>/dev/null; then
  curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
    | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
  echo "deb [arch=${ARCH} signed-by=/etc/apt/keyrings/docker.gpg] \
https://download.docker.com/linux/ubuntu $(lsb_release -cs) 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-compose-plugin
  sudo usermod -aG docker "$USER"
  ok "Docker installiert"
else
  ok "Docker bereits vorhanden ($(docker --version))"
fi

# ── 5. Node.js 22 + Claude Code installieren ──────────────────────────────
step "5/11 Node.js 22 + Claude Code installieren"
if ! command -v node &>/dev/null; then
  curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
  sudo apt-get install -y -qq nodejs
  ok "Node.js $(node --version) installiert"
else
  ok "Node.js bereits vorhanden ($(node --version))"
fi

if ! command -v claude &>/dev/null; then
  sudo npm install -g @anthropic-ai/claude-code
  ok "Claude Code installiert"
else
  ok "Claude Code bereits vorhanden"
fi

# ── 6. MCP-Konfiguration ──────────────────────────────────────────────────
step "6/11 Claude Code MCP konfigurieren"
mkdir -p "$CLAUDE_CONFIG_DIR"
cat > "$CLAUDE_CONFIG_DIR/settings.json" << MCPEOF
{
  "mcpServers": {
    "gitlab-carbacan": {
      "url": "$MCP_URL"
    }
  }
}
MCPEOF
ok "MCP konfiguriert → $MCP_URL"

# ── 7. VS Code installieren ────────────────────────────────────────────────
step "7/11 Visual Studio Code installieren"
if ! command -v code &>/dev/null; then
  VSCODE_INSTALLED=false

  if [ "$ARCH" = "arm64" ]; then
    echo "  arm64 — lade VS Code arm64 .deb..." > /dev/tty
    wget -q "https://code.visualstudio.com/sha/download?build=stable&os=linux-deb-arm64" \
      -O /tmp/vscode-arm64.deb && \
    sudo dpkg -i /tmp/vscode-arm64.deb && \
    rm -f /tmp/vscode-arm64.deb && \
    VSCODE_INSTALLED=true || { rm -f /tmp/vscode-arm64.deb; true; }
  fi

  if ! $VSCODE_INSTALLED; then
    wget -qO- https://packages.microsoft.com/keys/microsoft.asc \
      | gpg --dearmor > /tmp/ms.gpg 2>/dev/null && \
    sudo install -o root -g root -m 644 /tmp/ms.gpg /etc/apt/trusted.gpg.d/ && \
    echo "deb [arch=amd64] https://packages.microsoft.com/repos/code stable main" \
      | sudo tee /etc/apt/sources.list.d/vscode.list > /dev/null && \
    sudo apt-get update -qq && \
    sudo apt-get install -y -qq code && \
    VSCODE_INSTALLED=true || true
  fi

  if ! $VSCODE_INSTALLED; then
    sudo snap install code --classic 2>/dev/null && VSCODE_INSTALLED=true || true
  fi

  if $VSCODE_INSTALLED; then
    code --install-extension golang.go                        2>/dev/null || true
    code --install-extension ms-vscode.vscode-typescript-next 2>/dev/null || true
    code --install-extension eamodio.gitlens                  2>/dev/null || true
    code --install-extension ms-azuretools.vscode-docker      2>/dev/null || true
    code --install-extension esbenp.prettier-vscode           2>/dev/null || true
    ok "VS Code + Extensions installiert"
  else
    warn "VS Code konnte nicht automatisch installiert werden"
    warn "Bitte manuell: https://code.visualstudio.com/download"
  fi
else
  ok "VS Code bereits vorhanden"
fi

# ── 8. Browser installieren ───────────────────────────────────────────────
step "8/11 Browser installieren"
if ! command -v google-chrome &>/dev/null && ! command -v google-chrome-stable &>/dev/null && \
   ! command -v chromium-browser &>/dev/null && ! command -v chromium &>/dev/null; then
  BROWSER_INSTALLED=false

  if [ "$ARCH" = "arm64" ]; then
    warn "Google Chrome hat kein arm64 Linux Build — installiere Chromium"
    sudo apt-get install -y -qq chromium-browser 2>/dev/null && BROWSER_INSTALLED=true || \
      { sudo snap install chromium 2>/dev/null && BROWSER_INSTALLED=true || true; }
    $BROWSER_INSTALLED && ok "Chromium (arm64) installiert" || \
      warn "Browser manuell: sudo apt install chromium-browser"
  else
    wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \
      -O /tmp/chrome.deb && \
    sudo dpkg -i /tmp/chrome.deb && rm -f /tmp/chrome.deb && BROWSER_INSTALLED=true || \
    { rm -f /tmp/chrome.deb; true; }
    $BROWSER_INSTALLED && ok "Google Chrome installiert" || \
      warn "Chrome manuell: https://www.google.com/chrome/"
  fi
else
  ok "Browser bereits vorhanden"
fi

# ── 9. Rocket.Chat ────────────────────────────────────────────────────────
step "9/11 Rocket.Chat installieren"
if ! dpkg -l 2>/dev/null | grep -qi rocketchat && ! snap list 2>/dev/null | grep -qi rocketchat; then
  RC_INSTALLED=false

  if [ "$ARCH" = "arm64" ]; then
    # Rocket.Chat hat kein Linux arm64 Build (weder .deb noch snap)
    # → Web-App-Shortcut im Browser anlegen
    warn "Kein Rocket.Chat Desktop für arm64 verfügbar — Web-App wird eingerichtet"
    RC_INSTALLED=true  # Web-Shortcut wird weiter unten bei Desktop-Links erstellt
  else
    RC_VERSION="3.9.14"
    RC_URL="https://github.com/RocketChat/Rocket.Chat.Electron/releases/download/${RC_VERSION}/rocketchat-${RC_VERSION}-amd64.deb"
    wget -q "$RC_URL" -O "/tmp/rocketchat.deb" 2>/dev/null && \
      sudo dpkg -i "/tmp/rocketchat.deb" && rm -f "/tmp/rocketchat.deb" && RC_INSTALLED=true || \
    { rm -f "/tmp/rocketchat.deb"
      sudo snap install rocketchat-desktop 2>/dev/null && RC_INSTALLED=true || true; }
    $RC_INSTALLED && ok "Rocket.Chat Desktop installiert" || \
      warn "Rocket.Chat manuell: https://rocket.chat/download"
  fi
else
  ok "Rocket.Chat Desktop bereits vorhanden"
fi

# ── 10. Nextcloud Desktop-Client ──────────────────────────────────────────
step "10/11 Nextcloud Desktop-Client installieren"
if ! command -v nextcloud &>/dev/null && ! dpkg -l 2>/dev/null | grep -qi nextcloud-desktop; then
  NC_INSTALLED=false

  if [ "$ARCH" = "arm64" ]; then
    sudo snap install nextcloud-desktop-client 2>/dev/null && NC_INSTALLED=true || true
  else
    sudo add-apt-repository -y ppa:nextcloud-devs/client 2>/dev/null || true
    sudo apt-get update -qq
    sudo apt-get install -y -qq nextcloud-desktop 2>/dev/null && NC_INSTALLED=true || \
      { sudo snap install nextcloud-desktop-client 2>/dev/null && NC_INSTALLED=true || true; }
  fi

  $NC_INSTALLED && ok "Nextcloud Desktop-Client installiert" || \
    warn "Nextcloud-Client manuell: https://nextcloud.com/install/#install-clients"
else
  ok "Nextcloud Desktop-Client bereits vorhanden"
fi

# ── 11. Mail-Client (Thunderbird) ─────────────────────────────────────────
step "11/11 Thunderbird Mail-Client installieren"
if ! command -v thunderbird &>/dev/null; then
  sudo apt-get install -y -qq thunderbird 2>/dev/null && ok "Thunderbird installiert" || \
    { sudo snap install thunderbird 2>/dev/null && ok "Thunderbird via snap installiert" || \
      warn "Thunderbird manuell installieren"; }
else
  ok "Thunderbird bereits vorhanden"
fi

# ── Go (optional, für dms-api Entwicklung) ────────────────────────────────
if ! command -v go &>/dev/null; then
  GO_VERSION="1.24.0"
  if [ "$ARCH" = "arm64" ]; then
    GO_TARBALL="go${GO_VERSION}.linux-arm64.tar.gz"
  else
    GO_TARBALL="go${GO_VERSION}.linux-amd64.tar.gz"
  fi
  wget -q "https://go.dev/dl/${GO_TARBALL}" -O /tmp/go.tar.gz
  sudo rm -rf /usr/local/go
  sudo tar -C /usr/local -xzf /tmp/go.tar.gz
  rm /tmp/go.tar.gz
  echo 'export PATH=$PATH:/usr/local/go/bin' >> "$HOME/.bashrc"
  echo 'export GOPATH=$HOME/go' >> "$HOME/.bashrc"
  ok "Go ${GO_VERSION} installiert (${ARCH})"
fi

# ── Repos klonen ──────────────────────────────────────────────────────────
step "Carbacan-Repos klonen"
mkdir -p "$HOME/carbacan"
CLONE_FAILED=false
for REPO in dms-api dms-frontend dms-deploy dms-docs dev-environment; do
  TARGET="$HOME/carbacan/$REPO"
  if [ ! -d "$TARGET" ]; then
    git clone "git@gitlab.carbacan.dev:carbacan/${REPO}.git" "$TARGET" 2>/dev/null \
      && ok "Geklont: $REPO" \
      || { warn "Klonen fehlgeschlagen: $REPO"; CLONE_FAILED=true; }
  else
    ok "Existiert bereits: $REPO"
  fi
done

# SSH-Key nochmal zeigen wenn Klonen fehlgeschlagen
if $CLONE_FAILED; then
  echo "" > /dev/tty
  echo -e "${RED}  SSH-Verbindung zu GitLab fehlgeschlagen!${NC}" > /dev/tty
  echo "" > /dev/tty
  echo -e "  Mögliche Ursachen:" > /dev/tty
  echo -e "  • Public Key noch nicht in GitLab hinterlegt" > /dev/tty
  echo -e "  • Falscher GitLab-Account" > /dev/tty
  echo "" > /dev/tty
  show_ssh_key_instructions
  echo "" > /dev/tty
  printf "  Key jetzt hinterlegen und ENTER drücken zum Wiederholen (oder Strg+C zum Überspringen): " > /dev/tty
  read -r _RETRY < "$TTY_IN"

  for REPO in dms-api dms-frontend dms-deploy dms-docs dev-environment; do
    TARGET="$HOME/carbacan/$REPO"
    if [ ! -d "$TARGET" ]; then
      git clone "git@gitlab.carbacan.dev:carbacan/${REPO}.git" "$TARGET" 2>/dev/null \
        && ok "Geklont: $REPO" \
        || warn "Klonen fehlgeschlagen: $REPO — bitte später manuell: git clone git@gitlab.carbacan.dev:carbacan/${REPO}.git ~/carbacan/${REPO}"
    fi
  done
fi

# ── Desktop-Verknüpfungen anlegen ─────────────────────────────────────────
DESKTOP_DIR="$HOME/Desktop"
mkdir -p "$DESKTOP_DIR"

BROWSER_CMD="google-chrome-stable"
command -v google-chrome-stable &>/dev/null || \
  { command -v google-chrome &>/dev/null && BROWSER_CMD="google-chrome"; } || \
  { command -v chromium-browser &>/dev/null && BROWSER_CMD="chromium-browser"; } || \
  { command -v chromium &>/dev/null && BROWSER_CMD="chromium"; }

cat > "$DESKTOP_DIR/Carbacan-GitLab.desktop" << DEOF
[Desktop Entry]
Type=Application
Name=GitLab Carbacan
Exec=$BROWSER_CMD --app=$GITLAB_URL
Icon=browser
Terminal=false
DEOF

cat > "$DESKTOP_DIR/Carbacan-Grafana.desktop" << DEOF
[Desktop Entry]
Type=Application
Name=Grafana Dashboard
Exec=$BROWSER_CMD --app=https://grafana.carbacan.dev
Icon=browser
Terminal=false
DEOF

# Rocket.Chat als Web-App auf arm64 (kein Desktop-Client verfügbar)
if [ "$ARCH" = "arm64" ]; then
  cat > "$DESKTOP_DIR/Carbacan-RocketChat.desktop" << DEOF
[Desktop Entry]
Type=Application
Name=Rocket.Chat (Web)
Exec=$BROWSER_CMD --app=$ROCKETCHAT_URL
Icon=browser
Terminal=false
DEOF
fi

chmod +x "$DESKTOP_DIR"/*.desktop 2>/dev/null || true

# ── Abschluss ─────────────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║            Setup abgeschlossen! ✓                   ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════════════╝${NC}"
echo ""
echo "  Architektur: $ARCH"
echo ""
echo "  Installiert:"
echo "  • Git ($GIT_NAME <$GIT_EMAIL>)"
echo "  • Docker"
echo "  • Node.js 22 + Claude Code"
echo "  • Claude MCP → $MCP_URL"
echo "  • VS Code + Extensions"
if [ "$ARCH" = "arm64" ]; then
echo "  • Chromium (arm64, Chrome-Ersatz)"
echo "  • Rocket.Chat als Web-App (kein arm64 Desktop-Client)"
else
echo "  • Google Chrome"
echo "  • Rocket.Chat Desktop"
fi
echo "  • Nextcloud Desktop-Client"
echo "  • Thunderbird (Mail)"
echo "  • Go 1.24 (${ARCH})"
echo ""
echo -e "${YELLOW}  Nächste Schritte:${NC}"
echo "  1. Abmelden + neu anmelden (Docker-Gruppe aktiv)"
echo "  2. Nextcloud-Client starten → $NEXTCLOUD_URL"
if [ "$ARCH" = "arm64" ]; then
echo "  3. Rocket.Chat öffnen → $ROCKETCHAT_URL (im Browser)"
else
echo "  3. Rocket.Chat Desktop starten"
fi
echo "  4. Browser öffnen → $GITLAB_URL"
echo "  5. claude auth → API-Key eingeben"
echo ""
echo -e "${BLUE}  Repos liegen in: ~/carbacan/${NC}"
echo ""
