#!/bin/bash # 🏭 MYP Backend - Installations-Skript # Installiert das Backend für Produktionsbetrieb oder Entwicklung set -e # Farbcodes für Ausgabe RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[0;33m' BLUE='\033[0;34m' NC='\033[0m' # No Color # Funktion zur Ausgabe mit Zeitstempel log() { echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1" } success_log() { echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] SUCCESS:${NC} $1" } warning_log() { echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1" } error_log() { echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] FEHLER:${NC} $1" >&2 } # Banner echo "========================================" echo "🏭 MYP Backend - Installation" echo "========================================" echo "" # Arbeitsverzeichnis SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd "$SCRIPT_DIR" log "Arbeitsverzeichnis: $SCRIPT_DIR" # Installation-Modus bestimmen INSTALL_MODE="development" if [ "$1" = "--production" ]; then INSTALL_MODE="production" log "🚀 Produktions-Installation gewählt" elif [ "$1" = "--development" ]; then INSTALL_MODE="development" log "🔧 Entwicklungs-Installation gewählt" else echo "Wählen Sie den Installationsmodus:" echo "1) Entwicklung (empfohlen für lokale Tests)" echo "2) Produktion (für Server-Deployment)" read -p "Ihre Wahl (1/2): " choice case $choice in 1) INSTALL_MODE="development" ;; 2) INSTALL_MODE="production" ;; *) log "Verwende Standard-Entwicklungsmodus" && INSTALL_MODE="development" ;; esac fi log "Installationsmodus: $INSTALL_MODE" # Bereinige vorherige Installation cleanup_existing_installation() { log "🧹 Bereinige vorherige Installation..." # Stoppe laufende Prozesse if pgrep -f "flask run" > /dev/null; then log "Stoppe laufende Flask-Prozesse..." pkill -f "flask run" || true fi if pgrep -f "gunicorn" > /dev/null; then log "Stoppe laufende Gunicorn-Prozesse..." pkill -f "gunicorn.*wsgi:application" || true fi # Entferne alte virtuelle Umgebung if [ -d "venv" ]; then log "Entferne alte virtuelle Umgebung..." rm -rf venv fi success_log "Bereinigung abgeschlossen" } # System-Dependencies prüfen und installieren install_system_dependencies() { log "🔧 Prüfe System-Dependencies..." # Betriebssystem erkennen if [ -f /etc/os-release ]; then . /etc/os-release OS=$NAME VER=$VERSION_ID elif type lsb_release >/dev/null 2>&1; then OS=$(lsb_release -si) VER=$(lsb_release -sr) else OS=$(uname -s) VER=$(uname -r) fi log "Erkanntes System: $OS $VER" # Python 3 prüfen if ! command -v python3 &> /dev/null; then error_log "Python 3 ist nicht installiert!" log "Installationsanleitung:" if [[ "$OS" == *"Ubuntu"* ]] || [[ "$OS" == *"Debian"* ]]; then log "sudo apt update && sudo apt install python3 python3-pip python3-venv" elif [[ "$OS" == *"CentOS"* ]] || [[ "$OS" == *"Red Hat"* ]]; then log "sudo yum install python3 python3-pip" elif [[ "$OS" == *"Alpine"* ]]; then log "sudo apk add python3 py3-pip" else log "Bitte installieren Sie Python 3 manuell für Ihr System" fi exit 1 fi # Python-Version prüfen PYTHON_VERSION=$(python3 -c "import sys; print('.'.join(map(str, sys.version_info[:2])))") log "Python-Version: $PYTHON_VERSION" if python3 -c "import sys; exit(0 if sys.version_info >= (3, 8) else 1)"; then success_log "Python-Version ist kompatibel (>= 3.8)" else error_log "Python-Version ist zu alt! Benötigt wird mindestens Python 3.8" exit 1 fi # pip prüfen if ! command -v pip3 &> /dev/null; then error_log "pip3 ist nicht installiert!" log "Installiere pip3..." if [[ "$OS" == *"Ubuntu"* ]] || [[ "$OS" == *"Debian"* ]]; then sudo apt install python3-pip else error_log "Bitte installieren Sie pip3 manuell" exit 1 fi fi # Weitere notwendige System-Pakete prüfen if [[ "$OS" == *"Ubuntu"* ]] || [[ "$OS" == *"Debian"* ]]; then log "Prüfe System-Pakete für Ubuntu/Debian..." # Prüfe ob build-essential installiert ist (für Compilation von Python-Paketen) if ! dpkg -l | grep -q build-essential; then log "Installiere build-essential..." sudo apt update sudo apt install -y build-essential python3-dev fi # Prüfe curl für Health-Checks if ! command -v curl &> /dev/null; then log "Installiere curl..." sudo apt install -y curl fi fi success_log "System-Dependencies sind verfügbar" } # Python virtuelle Umgebung erstellen create_virtual_environment() { log "🐍 Erstelle Python virtuelle Umgebung..." # Erstelle virtuelle Umgebung python3 -m venv venv # Aktiviere virtuelle Umgebung source venv/bin/activate # Upgrade pip in virtueller Umgebung log "Aktualisiere pip..." pip install --upgrade pip success_log "Virtuelle Umgebung erstellt und aktiviert" } # Python-Dependencies installieren install_python_dependencies() { log "📦 Installiere Python-Dependencies..." # Aktiviere virtuelle Umgebung source venv/bin/activate # Installiere Requirements if [ -f "requirements.txt" ]; then log "Installiere aus requirements.txt..." pip install -r requirements.txt else error_log "requirements.txt nicht gefunden!" exit 1 fi # Produktions-spezifische Dependencies if [ "$INSTALL_MODE" = "production" ]; then log "Installiere Produktions-Dependencies..." pip install gunicorn supervisor fi success_log "Python-Dependencies installiert" } # Konfiguration vorbereiten prepare_configuration() { log "⚙️ Bereite Konfiguration vor..." # Erstelle notwendige Verzeichnisse mkdir -p instance logs migrations/versions # Kopiere Beispiel-Umgebungsvariablen falls nicht vorhanden if [ ! -f "env.backend" ]; then if [ -f "env.example" ]; then log "Erstelle env.backend aus Vorlage..." cp env.example env.backend else log "Erstelle Standard env.backend..." cat > env.backend << EOF # MYP Backend Konfiguration FLASK_ENV=$INSTALL_MODE SECRET_KEY=7445630171969DFAC92C53CEC92E67A9CB2E00B3CB2F DATABASE_PATH=instance/myp.db LOG_LEVEL=INFO JOB_CHECK_INTERVAL=60 PRINTERS={"Drucker 1": {"ip": "192.168.0.100"}, "Drucker 2": {"ip": "192.168.0.101"}, "Drucker 3": {"ip": "192.168.0.102"}, "Drucker 4": {"ip": "192.168.0.103"}, "Drucker 5": {"ip": "192.168.0.104"}, "Drucker 6": {"ip": "192.168.0.106"}} TAPO_USERNAME=till.tomczak@mercedes-benz.com TAPO_PASSWORD=744563017196A EOF fi warning_log "env.backend wurde erstellt. Bitte anpassen!" fi success_log "Konfiguration vorbereitet" } # Datenbank initialisieren initialize_database() { log "🗄️ Initialisiere Datenbank..." # Aktiviere virtuelle Umgebung source venv/bin/activate # Lade Umgebungsvariablen if [ -f "env.backend" ]; then export $(cat env.backend | grep -v '^#' | grep -v '^$' | xargs) fi # Setze Flask-App export FLASK_APP=app.py export FLASK_ENV=$INSTALL_MODE # Initialisiere Datenbank python3 -c " from app import create_app, init_db app = create_app('$INSTALL_MODE') with app.app_context(): init_db() print('✅ Datenbank initialisiert') " success_log "Datenbank initialisiert" } # Systemd-Service für Produktion erstellen create_systemd_service() { if [ "$INSTALL_MODE" = "production" ]; then log "🔧 Erstelle systemd-Service für Produktion..." SERVICE_FILE="/etc/systemd/system/myp-backend.service" sudo tee $SERVICE_FILE > /dev/null << EOF [Unit] Description=MYP Backend Flask Application After=network.target [Service] Type=exec User=$USER Group=$USER WorkingDirectory=$SCRIPT_DIR Environment=PATH=$SCRIPT_DIR/venv/bin EnvironmentFile=$SCRIPT_DIR/env.backend ExecStart=$SCRIPT_DIR/venv/bin/gunicorn --bind 0.0.0.0:5000 --workers 4 wsgi:application ExecReload=/bin/kill -s HUP \$MAINPID Restart=always RestartSec=10 [Install] WantedBy=multi-user.target EOF sudo systemctl daemon-reload sudo systemctl enable myp-backend success_log "Systemd-Service erstellt: myp-backend.service" log "Starten mit: sudo systemctl start myp-backend" log "Status prüfen mit: sudo systemctl status myp-backend" fi } # Hauptinstallation main() { cleanup_existing_installation install_system_dependencies create_virtual_environment install_python_dependencies prepare_configuration initialize_database create_systemd_service echo "" echo "========================================" success_log "🎉 Installation erfolgreich abgeschlossen!" echo "========================================" echo "" log "Nächste Schritte:" echo "" if [ "$INSTALL_MODE" = "production" ]; then echo "📋 Produktionsbetrieb:" echo " 1. Konfiguration prüfen: nano env.backend" echo " 2. Service starten: sudo systemctl start myp-backend" echo " 3. Service prüfen: sudo systemctl status myp-backend" echo " 4. Oder manuell: ./start-production.sh" else echo "🔧 Entwicklungsbetrieb:" echo " 1. Konfiguration prüfen: nano env.backend" echo " 2. Server starten: ./start-backend-server.sh" echo " 3. Development-Server: ./start-backend-server.sh --development" fi echo "" echo "📡 Backend wird verfügbar sein unter:" echo " - API: http://localhost:5000" echo " - Health-Check: http://localhost:5000/health" echo " - Test: http://localhost:5000/api/test" echo "" } # Installation starten main "$@"