diff --git a/server_scripts/auto_server_setup.sh b/server_scripts/auto_server_setup.sh index ec8901a..b1deacc 100644 --- a/server_scripts/auto_server_setup.sh +++ b/server_scripts/auto_server_setup.sh @@ -1,177 +1,201 @@ -#!/bin/bash +#!/usr/bin/env bash +# auto_server_setup.sh — Marco G. & ChatGPT — 2025-04-28 +# Prepara un home-server en Ubuntu 22.04/24.04 de forma (semi)automática. -# Exit immediately if a command exits with a non-zero status -set -e +set -euo pipefail -# ===================== -# Configuración inicial -# ===================== -SERVER_USER="marco" # <- Reemplaza con tu nombre de usuario en el servidor -INSTALL_PIHOLE="yes" # <- "yes" para instalar Pi-hole, "no" para omitir -INSTALL_CASAOS="yes" # <- "yes" para instalar CasaOS, "no" para omitir -AUTO_REBOOT="yes" # <- "yes" para reiniciar automáticamente, "no" para preguntar +LOG(){ printf "\n\e[1;32m▶ %s\e[0m\n" "$*"; } -# Logging function -LOG() { - echo -e "[`date +'%Y-%m-%d %H:%M:%S'`] $@" -} - -# Comprueba que el script se esté ejecutando como root -if [ "$(id -u)" -ne 0 ]; then - echo "Por favor, ejecuta este script como root o con sudo." - exit 1 +########################## +# 0. Comprobaciones previas +########################## +if [[ "$(id -u)" -ne 0 ]]; then + echo "⚠️ Este script debe ejecutarse como root (sudo)." + exit 1 fi -if ! id "$SERVER_USER" >/dev/null 2>&1; then - echo "Usuario $SERVER_USER no encontrado. Por favor verifica la configuración de SERVER_USER." - exit 1 -fi +############ CONFIGURACIÓN INTERACTIVA ############ +echo -e "\n--- Configuración interactiva ---" -# Función para instalar paquetes base -install_base_packages() { - LOG "Instalando paquetes base..." - export DEBIAN_FRONTEND=noninteractive - apt update && apt upgrade -y - apt install -y build-essential curl wget git ufw snapd lsb-release apt-transport-https ca-certificates gnupg +# 1) Usuario del sistema +DEFAULT_USER="${SUDO_USER:-$USER}" +read -rp "➤ Usuario a configurar [$DEFAULT_USER]: " TMP_USER +SERVER_USER="${TMP_USER:-$DEFAULT_USER}" + +# 2) ¿Instalar Pi-hole? +read -rp "➤ ¿Instalar Pi-hole? [Y/n]: " TMP_PIHOLE +INSTALL_PIHOLE="$( [[ ${TMP_PIHOLE,,} =~ ^n ]] && echo no || echo yes )" + +# 3) ¿Instalar CasaOS? +read -rp "➤ ¿Instalar CasaOS? [Y/n]: " TMP_CASAOS +INSTALL_CASAOS="$( [[ ${TMP_CASAOS,,} =~ ^n ]] && echo no || echo yes )" + +# 4) ¿Reiniciar automáticamente al terminar? +read -rp "➤ ¿Reiniciar automáticamente al terminar? [Y/n]: " TMP_REBOOT +AUTO_REBOOT="$( [[ ${TMP_REBOOT,,} =~ ^n ]] && echo no || echo yes )" + +echo -e "\nResumen:" +echo " SERVER_USER = $SERVER_USER" +echo " INSTALL_PIHOLE= $INSTALL_PIHOLE" +echo " INSTALL_CASAOS= $INSTALL_CASAOS" +echo " AUTO_REBOOT = $AUTO_REBOOT" +echo "-----------------------------------" +sleep 2 +##################################################### + +################################### +# 1. Base APT + actualizaciones +################################### +install_base() { + LOG "Actualizando APT y herramientas básicas…" + export DEBIAN_FRONTEND=noninteractive + apt update && apt -y full-upgrade + apt install -y git curl gnupg lsb-release nano \ + ca-certificates software-properties-common \ + apt-transport-https build-essential ufw } -# Función para instalar Zsh, Oh-My-Zsh, y zsh-autosuggestions -install_zsh_ohmyzsh() { - LOG "Instalando Zsh y Oh-My-Zsh..." - apt install -y zsh - - # Instalar Oh-My-Zsh para el usuario especificado - sudo -H -u "$SERVER_USER" bash -c "mkdir -p /tmp && curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh -o /tmp/install-ohmyzsh.sh" - sudo -H -u "$SERVER_USER" bash -c "bash /tmp/install-ohmyzsh.sh --unattended" - - # Cambiar el shell predeterminado del usuario a zsh - chsh -s "$(which zsh)" "$SERVER_USER" - - # Instalar plugin zsh-autosuggestions - LOG "Instalando complemento zsh-autosuggestions..." - sudo -H -u "$SERVER_USER" git clone https://github.com/zsh-users/zsh-autosuggestions "/home/$SERVER_USER/.oh-my-zsh/custom/plugins/zsh-autosuggestions" - - # Habilitar el plugin zsh-autosuggestions en el .zshrc del usuario - sudo -H -u "$SERVER_USER" sed -i 's/plugins=(git)/plugins=(git zsh-autosuggestions)/' "/home/$SERVER_USER/.zshrc" +################################### +# 2. Zsh + Oh-My-Zsh + autosuggestions +################################### +install_shell() { + LOG "Instalando Zsh y Oh-My-Zsh…" + apt install -y zsh + sudo -u "$SERVER_USER" mkdir -p /tmp + sudo -u "$SERVER_USER" curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh \ + -o /tmp/install-ohmyzsh.sh + sudo -u "$SERVER_USER" bash /tmp/install-ohmyzsh.sh --unattended + chsh -s "$(command -v zsh)" "$SERVER_USER" + + LOG "Instalando plugin zsh-autosuggestions…" + sudo -u "$SERVER_USER" git clone --depth=1 https://github.com/zsh-users/zsh-autosuggestions \ + "/home/$SERVER_USER/.oh-my-zsh/custom/plugins/zsh-autosuggestions" + sudo -u "$SERVER_USER" sed -i 's/plugins=(git)/plugins=(git zsh-autosuggestions)/' \ + "/home/$SERVER_USER/.zshrc" } -# Función para instalar fzf y btop -install_fzf_btop() { - LOG "Instalando fzf y btop..." - apt install -y fzf btop +################################### +# 3. Utilidades extra (fzf, btop) +################################### +install_utils() { + LOG "Instalando fzf y btop…" + apt install -y fzf btop } -# Función para instalar Certbot mediante snap +################################### +# 4. Certbot (Let’s Encrypt) +################################### install_certbot() { - LOG "Instalando Certbot (snap)..." - # Asegurarse de que snap core esté instalado y actualizado - snap install core || true - snap refresh core - # Instalar Certbot - snap install --classic certbot - ln -s /snap/certbot/current/bin/certbot /usr/bin/certbot || true + LOG "Instalando Certbot (snap)…" + snap install core --classic >/dev/null || true + snap refresh core + snap install --classic certbot + ln -sf /snap/bin/certbot /usr/bin/certbot } -# Función para instalar Docker Engine y docker-compose plugin +################################### +# 5. Docker Engine + compose-plugin +################################### install_docker() { - LOG "Instalando Docker Engine y Docker Compose Plugin..." - # Desinstalar versiones antiguas de Docker si existen - apt remove -y docker docker.io containerd runc || true - - # Instalar paquetes de soporte - apt install -y ca-certificates curl gnupg - - # Agregar clave GPG oficial de Docker - install -m 0755 -d /etc/apt/keyrings - curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg - - # Agregar repositorio de Docker - source /etc/os-release - echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $VERSION_CODENAME stable" > /etc/apt/sources.list.d/docker.list - - # Instalar Docker Engine, CLI, Containerd, Buildx y Compose - apt update - apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin - - # Agregar el usuario al grupo docker para evitar usar sudo con Docker - usermod -aG docker "$SERVER_USER" || true - LOG "Docker Engine y Docker Compose instalados." + LOG "Instalando Docker Engine…" + apt remove -y docker docker.io containerd runc || true + install -m0755 -d /etc/apt/keyrings + curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \ + gpg --dearmor -o /etc/apt/keyrings/docker.gpg + source /etc/os-release + echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \ +https://download.docker.com/linux/ubuntu ${VERSION_CODENAME} stable" \ + > /etc/apt/sources.list.d/docker.list + apt update + apt install -y docker-ce docker-ce-cli containerd.io \ + docker-buildx-plugin docker-compose-plugin + usermod -aG docker "$SERVER_USER" } -# Función para instalar ZeroTier One +################################### +# 6. ZeroTier One +################################### install_zerotier() { - LOG "Instalando ZeroTier One..." - curl -fsSL https://install.zerotier.com | bash + LOG "Instalando ZeroTier…" + curl -s https://install.zerotier.com | bash } -# Función para desplegar Portainer en un contenedor Docker +################################### +# 7. Portainer (contenedor Docker) +################################### install_portainer() { - LOG "Desplegando Portainer (contenedor Docker)..." - docker volume create portainer_data || true - docker run -d \ - -p 8000:8000 -p 9000:9000 -p 9443:9443 \ - --name portainer --restart=always \ - -v /var/run/docker.sock:/var/run/docker.sock \ - -v portainer_data:/data \ - portainer/portainer-ce:latest + LOG "Desplegando Portainer CE…" + docker volume create portainer_data + docker run -d --name portainer \ + -p 8000:8000 -p 9443:9443 \ + --restart=always \ + -v /var/run/docker.sock:/var/run/docker.sock \ + -v portainer_data:/data \ + portainer/portainer-ce:latest } -# Función opcional para instalar CasaOS +################################### +# 8. CasaOS (opcional) +################################### install_casaos() { - if [ "$INSTALL_CASAOS" = "yes" ]; then - LOG "Instalando CasaOS..." - curl -fsSL https://get.casaos.io | bash - fi + [[ "$INSTALL_CASAOS" == "no" ]] && return + LOG "Instalando CasaOS…" + curl -fsSL https://get.casaos.io | bash } -# Función opcional para instalar Pi-hole +################################### +# 9. Pi-hole (opcional, nativo) +################################### install_pihole() { - if [ "$INSTALL_PIHOLE" = "yes" ]; then - LOG "Instalando Pi-hole (puede tardar unos minutos)..." - curl -fsSL https://install.pi-hole.net | bash -s -- --unattended - fi + [[ "$INSTALL_PIHOLE" == "no" ]] && return + LOG "Instalando Pi-hole… (modo unattended)" + export PIHOLE_SKIP_OS_CHECK=true + curl -sSL https://install.pi-hole.net | bash -s -- --unattended } -# Función para instalar Plex Media Server +################################### +# 10. Plex Media Server (nativo) +################################### install_plex() { - LOG "Instalando Plex Media Server..." - # Agregar clave y repositorio de Plex - curl -fsSL https://downloads.plex.tv/plex-keys/PlexSign.key | gpg --dearmor -o /etc/apt/trusted.gpg.d/plex.gpg - echo "deb [signed-by=/etc/apt/trusted.gpg.d/plex.gpg] https://downloads.plex.tv/repo/deb/ public main" > /etc/apt/sources.list.d/plexmediaserver.list - apt update - apt install -y plexmediaserver + LOG "Instalando Plex Media Server…" + curl -fsSL https://downloads.plex.tv/plex-keys/PlexSign.key | \ + gpg --dearmor -o /etc/apt/trusted.gpg.d/plex.gpg + echo "deb [signed-by=/etc/apt/trusted.gpg.d/plex.gpg] https://downloads.plex.tv/repo/deb/ public main" \ + > /etc/apt/sources.list.d/plexmediaserver.list + apt update + apt install -y plexmediaserver } -# Función principal para ejecutar todas las instalaciones -main_setup() { - install_base_packages - install_zsh_ohmyzsh - install_fzf_btop - install_certbot - install_docker - install_zerotier - install_portainer - install_casaos - install_pihole - install_plex - - LOG "Configuración finalizada." - if [ "$AUTO_REBOOT" = "yes" ]; then - LOG "Reiniciando el sistema en 5 segundos..." - sleep 5 - reboot +############################ +# Ejecución en cascada +############################ +main() { + install_base + install_shell + install_utils + install_certbot + install_docker + install_zerotier + install_portainer + install_casaos + install_pihole + install_plex + + LOG "🎉 Instalación completa." + LOG "Accesos:\n • Portainer → https://:9443\n • CasaOS → http://\n • Plex → http://:32400/web\n • Pi-hole → http:///admin" + + if [[ "$AUTO_REBOOT" == "yes" ]]; then + LOG "Reiniciando en 10 s… (Ctrl-C para abortar)" + sleep 10 && reboot + else + read -rp $'\n¿Deseas reiniciar ahora? [y/N]: ' REPLY + if [[ ${REPLY,,} == "y" ]]; then + LOG "Reiniciando…" + reboot else - echo -n "¿Desea reiniciar el servidor ahora? (s/N): " - read -r CONFIRM - if [[ "$CONFIRM" =~ ^([sS][iI]?|[yY])$ ]]; then - LOG "Reiniciando el sistema..." - sleep 2 - reboot - else - LOG "Instalación completada. Reinicia manualmente para aplicar los cambios." - fi + LOG "No se reinició. Hazlo manualmente cuando quieras." fi + fi } -# Ejecutar el proceso principal -main_setup +main "$@"