#!/usr/bin/env bash # ============================================================================= # VPS Monitor Agent — script d'installation / mise à jour # Télécharge les fichiers depuis le dépôt Gitea et configure un service systemd. # # Usage : # sudo bash install.sh [--port PORT] [--key API_KEY] [--branch BRANCH] # sudo bash install.sh --update [--branch BRANCH] # sudo bash install.sh --uninstall # ============================================================================= set -euo pipefail # Redirige stderr vers stdout pour que les erreurs soient visibles en mode pipe exec 2>&1 echo "==================================================" echo " VPS Monitor Agent — démarrage du script" echo "==================================================" # ─── Constantes ─────────────────────────────────────────────────────────────── REPO_BASE="https://git.jeanbonapp.com/jeanbon/ScriptVPS/raw/branch" REPO_FILES=( "vps-monitor/agent/agent.py" "vps-monitor/agent/requirements.txt" ) INSTALL_DIR="/opt/vps-monitor-agent" SERVICE_NAME="vps-monitor-agent" SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service" DEFAULT_PORT=8001 DEFAULT_BRANCH="main" # ─── Couleurs ───────────────────────────────────────────────────────────────── RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m' info() { echo -e "${CYAN}[INFO]${NC} $*"; } success() { echo -e "${GREEN}[OK]${NC} $*"; } warn() { echo -e "${YELLOW}[WARN]${NC} $*"; } error() { echo -e "${RED}[ERROR]${NC} $*" >&2; exit 1; } # ─── Arguments ──────────────────────────────────────────────────────────────── AGENT_PORT=$DEFAULT_PORT AGENT_API_KEY="" REPO_BRANCH=$DEFAULT_BRANCH MODE="install" # install | update | uninstall while [[ $# -gt 0 ]]; do case $1 in --port) AGENT_PORT="$2"; shift 2 ;; --key) AGENT_API_KEY="$2"; shift 2 ;; --branch) REPO_BRANCH="$2"; shift 2 ;; --update) MODE="update"; shift ;; --uninstall) MODE="uninstall"; shift ;; *) error "Argument inconnu : $1. Voir INSTALL.md pour l'aide." ;; esac done # ─── Vérifications communes ─────────────────────────────────────────────────── check_root() { if [[ $EUID -ne 0 ]]; then error "Ce script doit être exécuté en root (sudo)." fi } check_deps() { command -v python3 &>/dev/null || error "Python 3 est requis : apt install python3 python3-venv" command -v docker &>/dev/null || error "Docker est requis. Consultez https://docs.docker.com/engine/install/" command -v curl &>/dev/null || error "curl est requis : apt install curl" } # ─── Téléchargement des fichiers depuis le dépôt ───────────────────────────── download_files() { info "Téléchargement des fichiers (branche : ${REPO_BRANCH})..." mkdir -p "$INSTALL_DIR" for file in "${REPO_FILES[@]}"; do filename=$(basename "$file") url="${REPO_BASE}/${REPO_BRANCH}/${file}" info " ↓ $filename" curl -fsSL "$url" -o "$INSTALL_DIR/$filename" \ || error "Impossible de télécharger : $url" done success "Fichiers téléchargés." } # ─── Désinstallation ────────────────────────────────────────────────────────── if [[ "$MODE" == "uninstall" ]]; then check_root info "Désinstallation de l'agent..." systemctl stop "$SERVICE_NAME" 2>/dev/null || true systemctl disable "$SERVICE_NAME" 2>/dev/null || true rm -f "$SERVICE_FILE" systemctl daemon-reload rm -rf "$INSTALL_DIR" success "Agent désinstallé." exit 0 fi # ─── Mise à jour ────────────────────────────────────────────────────────────── if [[ "$MODE" == "update" ]]; then check_root [[ ! -d "$INSTALL_DIR" ]] && error "L'agent n'est pas installé. Lancez d'abord l'installation." info "Mise à jour de l'agent VPS Monitor..." # Conserver la clé API et le port existants if [[ -f "$INSTALL_DIR/.env" ]]; then AGENT_API_KEY=$(grep -E '^AGENT_API_KEY=' "$INSTALL_DIR/.env" | cut -d= -f2- || true) SAVED_PORT=$(grep -E '^AGENT_PORT=' "$INSTALL_DIR/.env" | cut -d= -f2- || true) [[ -n "$SAVED_PORT" ]] && AGENT_PORT="$SAVED_PORT" fi download_files info "Mise à jour des dépendances Python..." "$INSTALL_DIR/venv/bin/pip" install --quiet --upgrade pip "$INSTALL_DIR/venv/bin/pip" install --quiet -r "$INSTALL_DIR/requirements.txt" success "Dépendances à jour." info "Redémarrage du service..." systemctl restart "$SERVICE_NAME" sleep 2 if systemctl is-active --quiet "$SERVICE_NAME"; then success "Service redémarré avec succès." CURRENT_VERSION=$(curl -sf --max-time 3 \ "http://localhost:${AGENT_PORT}/health" 2>/dev/null | python3 -c \ "import sys,json; d=json.load(sys.stdin); print(d.get('version','?'))" 2>/dev/null || echo "?") echo -e "\n${GREEN}Mise à jour terminée.${NC} Version active : ${CYAN}${CURRENT_VERSION}${NC}\n" else warn "Le service ne semble pas actif après la mise à jour." echo " journalctl -u ${SERVICE_NAME} -n 30 --no-pager" exit 1 fi exit 0 fi # ─── Installation ───────────────────────────────────────────────────────────── check_root check_deps info "Python : $(python3 --version)" info "Docker : $(docker --version)" # Clé API : fournie > existante > générée if [[ -z "$AGENT_API_KEY" ]]; then if [[ -f "$INSTALL_DIR/.env" ]]; then AGENT_API_KEY=$(grep -E '^AGENT_API_KEY=' "$INSTALL_DIR/.env" | cut -d= -f2- || true) [[ -n "$AGENT_API_KEY" ]] && info "Clé API existante conservée." fi if [[ -z "$AGENT_API_KEY" ]]; then AGENT_API_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))") warn "Aucune clé fournie — clé aléatoire générée." fi fi download_files # ─── Environnement virtuel ──────────────────────────────────────────────────── if [[ ! -d "$INSTALL_DIR/venv" ]]; then info "Création de l'environnement virtuel Python..." python3 -m venv "$INSTALL_DIR/venv" fi info "Installation des dépendances Python..." "$INSTALL_DIR/venv/bin/pip" install --quiet --upgrade pip "$INSTALL_DIR/venv/bin/pip" install --quiet -r "$INSTALL_DIR/requirements.txt" success "Dépendances installées." # ─── Fichier .env ───────────────────────────────────────────────────────────── cat > "$INSTALL_DIR/.env" < "$SERVICE_FILE" </dev/null \ || hostname -I | awk '{print $1}') echo "" echo -e "${GREEN}══════════════════════════════════════════════════${NC}" echo -e "${GREEN} Agent VPS Monitor installé avec succès !${NC}" echo -e "${GREEN}══════════════════════════════════════════════════${NC}" echo -e " Adresse : ${CYAN}http://${PUBLIC_IP}:${AGENT_PORT}${NC}" echo -e " Clé API : ${YELLOW}${AGENT_API_KEY}${NC}" echo -e " Branche : ${CYAN}${REPO_BRANCH}${NC}" echo "" echo -e " Commandes utiles :" echo -e " journalctl -u ${SERVICE_NAME} -f # logs en direct" echo -e " systemctl status ${SERVICE_NAME} # état du service" echo -e " sudo bash install.sh --update # mise à jour" echo -e " sudo bash install.sh --uninstall # désinstallation" echo -e "${GREEN}══════════════════════════════════════════════════${NC}" echo "" warn "Notez la clé API — elle est nécessaire pour configurer le backend central."