# MYP Installer Control Center # Zentrale Installationskonsole fuer die MYP-Plattform # Version 2.0 # Farbdefinitionen fuer bessere Lesbarkeit $ColorTitle = "Cyan" $ColorSuccess = "Green" $ColorError = "Red" $ColorWarning = "Yellow" $ColorInfo = "Blue" $ColorCommand = "White" # Ueberpruefen, ob das Skript als Administrator ausgefuehrt wird $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) function Show-Header { param ([string]$Title) Clear-Host Write-Host "=============================================================" -ForegroundColor $ColorTitle Write-Host " MYP INSTALLER CONTROL CENTER" -ForegroundColor $ColorTitle Write-Host "=============================================================" -ForegroundColor $ColorTitle Write-Host " $Title" -ForegroundColor $ColorTitle Write-Host "=============================================================" -ForegroundColor $ColorTitle if (-not $isAdmin) { Write-Host "HINWEIS: Dieses Skript laeuft ohne Administrator-Rechte." -ForegroundColor $ColorWarning Write-Host "Einige Funktionen sind moeglicherweise eingeschraenkt." -ForegroundColor $ColorWarning Write-Host "=============================================================" -ForegroundColor $ColorTitle } Write-Host "" } function Test-CommandExists { param ([string]$Command) try { Get-Command $Command -ErrorAction Stop | Out-Null return $true } catch { return $false } } function Exec-Command { param ( [string]$Command, [string]$Description ) Write-Host "> $Description..." -ForegroundColor $ColorInfo try { Invoke-Expression $Command | Out-Host if ($LASTEXITCODE -eq 0 -or $null -eq $LASTEXITCODE) { Write-Host "Erfolgreich abgeschlossen!" -ForegroundColor $ColorSuccess return $true } else { Write-Host "Fehler beim Ausfuehren des Befehls. Exit-Code: $LASTEXITCODE" -ForegroundColor $ColorError return $false } } catch { $errorMessage = $_.Exception.Message Write-Host "Fehler: $errorMessage" -ForegroundColor $ColorError return $false } } function Get-LocalIPAddress { $localIP = (Get-NetIPAddress | Where-Object { $_.AddressFamily -eq "IPv4" -and $_.PrefixOrigin -ne "WellKnown" } | Select-Object -First 1).IPAddress if (-not $localIP) { $localIP = "127.0.0.1" } return $localIP } function Test-Dependencies { Show-Header "Systemvoraussetzungen pruefen" Write-Host "Pruefe Abhaengigkeiten..." -ForegroundColor $ColorInfo $pythonInstalled = Test-CommandExists "python" if ($pythonInstalled) { Write-Host "Python gefunden" -ForegroundColor $ColorSuccess } else { Write-Host "Python nicht gefunden" -ForegroundColor $ColorError } $pipInstalled = Test-CommandExists "pip" if ($pipInstalled) { Write-Host "Pip gefunden" -ForegroundColor $ColorSuccess } else { Write-Host "Pip nicht gefunden" -ForegroundColor $ColorError } $dockerInstalled = Test-CommandExists "docker" if ($dockerInstalled) { Write-Host "Docker gefunden" -ForegroundColor $ColorSuccess } else { Write-Host "Docker nicht gefunden" -ForegroundColor $ColorError } $dockerComposeInstalled = Test-CommandExists "docker-compose" if ($dockerComposeInstalled) { Write-Host "Docker Compose gefunden" -ForegroundColor $ColorSuccess } else { Write-Host "Docker Compose nicht gefunden" -ForegroundColor $ColorError } $nodeInstalled = Test-CommandExists "node" if ($nodeInstalled) { Write-Host "Node.js gefunden" -ForegroundColor $ColorSuccess } else { Write-Host "Node.js nicht gefunden" -ForegroundColor $ColorError } $npmInstalled = Test-CommandExists "npm" if ($npmInstalled) { Write-Host "NPM gefunden" -ForegroundColor $ColorSuccess } else { Write-Host "NPM nicht gefunden" -ForegroundColor $ColorError } Write-Host "" Write-Host "Druecken Sie eine beliebige Taste, um fortzufahren..." $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } function Setup-Hosts { Show-Header "Host-Konfiguration" if (-not $isAdmin) { Write-Host "Diese Funktion erfordert Administrator-Rechte." -ForegroundColor $ColorError Write-Host "Bitte starten Sie das Skript als Administrator neu." -ForegroundColor $ColorWarning Write-Host "" Write-Host "Druecken Sie eine beliebige Taste, um fortzufahren..." $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") return } $localIP = Get-LocalIPAddress Write-Host "Lokale IP-Adresse: $localIP" -ForegroundColor $ColorSuccess $hostsFile = "$env:windir\System32\drivers\etc\hosts" Write-Host "Hosts-Datei: $hostsFile" -ForegroundColor $ColorInfo # Pruefen, ob die Eintraege bereits existieren $frontendEntry = Select-String -Path $hostsFile -Pattern "m040tbaraspi001.de040.corpintra.net" -Quiet $backendEntry = Select-String -Path $hostsFile -Pattern "raspberrypi" -Quiet # Eintraege in die Hosts-Datei schreiben Write-Host "Aktualisiere Hosts-Datei..." -ForegroundColor $ColorInfo $hostsContent = Get-Content -Path $hostsFile if (-not $frontendEntry) { $hostsContent += "" $hostsContent += "# MYP Frontend Host" $hostsContent += "$localIP m040tbaraspi001.de040.corpintra.net m040tbaraspi001" Write-Host "Frontend-Hostname hinzugefuegt" -ForegroundColor $ColorSuccess } else { Write-Host "Frontend-Hostname ist bereits konfiguriert" -ForegroundColor $ColorWarning } if (-not $backendEntry) { $hostsContent += "" $hostsContent += "# MYP Backend Host" $hostsContent += "$localIP raspberrypi" Write-Host "Backend-Hostname hinzugefuegt" -ForegroundColor $ColorSuccess } else { Write-Host "Backend-Hostname ist bereits konfiguriert" -ForegroundColor $ColorWarning } # Speichern der aktualisierten Hosts-Datei try { $hostsContent | Set-Content -Path $hostsFile -Force Write-Host "Konfiguration abgeschlossen!" -ForegroundColor $ColorSuccess } catch { $errorMessage = $_.Exception.Message Write-Host "Fehler beim Schreiben der Hosts-Datei: $errorMessage" -ForegroundColor $ColorError } Write-Host "" Write-Host "Folgende Hostnamen sind jetzt konfiguriert:" -ForegroundColor $ColorInfo Write-Host " - Frontend: m040tbaraspi001.de040.corpintra.net" -ForegroundColor $ColorCommand Write-Host " - Backend: raspberrypi" -ForegroundColor $ColorCommand Write-Host "" Write-Host "Druecken Sie eine beliebige Taste, um fortzufahren..." $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } function Create-SSLCertificates { Show-Header "SSL-Zertifikat-Generator" # Parameter definieren $certDir = "./backend/instance/ssl" $backendCertFile = "$certDir/myp.crt" $backendKeyFile = "$certDir/myp.key" $frontendCertFile = "$certDir/frontend.crt" $frontendKeyFile = "$certDir/frontend.key" Write-Host "Zertifikate werden fuer folgende Hostnamen erstellt:" -ForegroundColor $ColorInfo # Hostname-Auswahl Write-Host "1. Fuer lokale Entwicklung (localhost)" -ForegroundColor $ColorCommand Write-Host "2. Fuer Raspberry Pi Deployment (raspberrypi)" -ForegroundColor $ColorCommand Write-Host "3. Fuer Unternehmens-Setup (m040tbaraspi001.de040.corpintra.net)" -ForegroundColor $ColorCommand $inputText = "Waehlen Sie eine Option (1-3)" $choice = Read-Host $inputText $backendHostname = "localhost" $frontendHostname = "localhost" if ($choice -eq "2") { $backendHostname = "raspberrypi" $frontendHostname = "raspberrypi" } elseif ($choice -eq "3") { $backendHostname = "raspberrypi" $frontendHostname = "m040tbaraspi001.de040.corpintra.net" } Write-Host "Backend-Hostname: $backendHostname" -ForegroundColor $ColorInfo Write-Host "Frontend-Hostname: $frontendHostname" -ForegroundColor $ColorInfo Write-Host "" # Verzeichnis erstellen, falls es nicht existiert if (!(Test-Path $certDir)) { Write-Host "Erstelle Verzeichnis $certDir..." -ForegroundColor $ColorInfo New-Item -ItemType Directory -Path $certDir -Force | Out-Null } # SSL-Zertifikate mit Python und cryptography erstellen Write-Host "Erstelle SSL-Zertifikate mit Python..." -ForegroundColor $ColorInfo $pythonInstalled = Test-CommandExists "python" if ($pythonInstalled) { # Ueberpruefen, ob cryptography installiert ist $cryptographyInstalled = python -c "try: import cryptography; print('True'); except ImportError: print('False')" 2>$null if ($cryptographyInstalled -ne "True") { Write-Host "Installiere Python-Abhaengigkeit 'cryptography'..." -ForegroundColor $ColorWarning Exec-Command "pip install cryptography" "Installiere cryptography-Paket" } # Python-Skript zur Zertifikatserstellung $certScript = @" import os import datetime import sys from cryptography import x509 from cryptography.x509.oid import NameOID from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption def create_self_signed_cert(cert_path, key_path, hostname="localhost"): # Verzeichnis erstellen, falls es nicht existiert cert_dir = os.path.dirname(cert_path) if cert_dir and not os.path.exists(cert_dir): os.makedirs(cert_dir, exist_ok=True) # Privaten Schluessel generieren private_key = rsa.generate_private_key( public_exponent=65537, key_size=4096, ) # Schluesseldatei schreiben with open(key_path, "wb") as key_file: key_file.write(private_key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption() )) # Aktuelles Datum und Ablaufdatum berechnen now = datetime.datetime.now() valid_until = now + datetime.timedelta(days=3650) # 10 Jahre gueltig # Name fuer das Zertifikat erstellen subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, hostname), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Mercedes-Benz AG"), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, "Werk 040 Berlin"), x509.NameAttribute(NameOID.COUNTRY_NAME, "DE"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Berlin"), x509.NameAttribute(NameOID.LOCALITY_NAME, "Berlin") ]) # Zertifikat erstellen cert = x509.CertificateBuilder().subject_name( subject ).issuer_name( issuer ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( now ).not_valid_after( valid_until ).add_extension( x509.SubjectAlternativeName([ x509.DNSName(hostname), x509.DNSName("localhost") ]), critical=False, ).add_extension( x509.BasicConstraints(ca=True, path_length=None), critical=True ).add_extension( x509.KeyUsage( digital_signature=True, content_commitment=False, key_encipherment=True, data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True, encipher_only=False, decipher_only=False ), critical=True ).add_extension( x509.ExtendedKeyUsage([ x509.oid.ExtendedKeyUsageOID.SERVER_AUTH, x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH ]), critical=False ).sign(private_key, hashes.SHA256()) # Zertifikatsdatei schreiben with open(cert_path, "wb") as cert_file: cert_file.write(cert.public_bytes(Encoding.PEM)) print(f"Selbstsigniertes SSL-Zertifikat fuer '{hostname}' erstellt:") print(f"Zertifikat: {cert_path}") print(f"Schluessel: {key_path}") print(f"Gueltig fuer 10 Jahre.") # Backend-Zertifikat erstellen create_self_signed_cert('$backendCertFile', '$backendKeyFile', '$backendHostname') # Frontend-Zertifikat erstellen create_self_signed_cert('$frontendCertFile', '$frontendKeyFile', '$frontendHostname') "@ $tempScriptPath = ".\temp_cert_script.py" $certScript | Out-File -FilePath $tempScriptPath -Encoding utf8 # Python-Skript ausfuehren try { python $tempScriptPath Write-Host "SSL-Zertifikate erfolgreich erstellt!" -ForegroundColor $ColorSuccess } catch { $errorMessage = $_.Exception.Message Write-Host "Fehler beim Erstellen der SSL-Zertifikate: $errorMessage" -ForegroundColor $ColorError } finally { # Temporaeres Skript loeschen if (Test-Path $tempScriptPath) { Remove-Item -Path $tempScriptPath -Force } } } else { Write-Host "Python nicht gefunden. SSL-Zertifikate koennen nicht erstellt werden." -ForegroundColor $ColorError } # Zertifikate im System installieren (optional) if ($isAdmin) { $installCerts = Read-Host "Moechten Sie die Zertifikate im System installieren? (j/n)" if ($installCerts -eq "j") { if (Test-Path $backendCertFile) { Write-Host "Installiere Backend-Zertifikat im System..." -ForegroundColor $ColorInfo Exec-Command "certutil -addstore -f 'ROOT' '$backendCertFile'" "Installiere im Root-Zertifikatsspeicher" } if (Test-Path $frontendCertFile) { Write-Host "Installiere Frontend-Zertifikat im System..." -ForegroundColor $ColorInfo Exec-Command "certutil -addstore -f 'ROOT' '$frontendCertFile'" "Installiere im Root-Zertifikatsspeicher" } } } else { Write-Host "Hinweis: Um die Zertifikate im System zu installieren, starten Sie das Skript als Administrator." -ForegroundColor $ColorWarning } # Frontend fuer HTTPS konfigurieren Write-Host "" Write-Host "Moechten Sie das Frontend fuer HTTPS konfigurieren? (j/n)" -ForegroundColor $ColorInfo $configureFrontend = Read-Host if ($configureFrontend -ne "n") { Write-Host "Konfiguriere Frontend fuer HTTPS..." -ForegroundColor $ColorInfo # Kopiere Zertifikate ins Frontend-Verzeichnis $frontendSslDir = "./frontend/ssl" if (!(Test-Path $frontendSslDir)) { New-Item -ItemType Directory -Path $frontendSslDir -Force | Out-Null } if (Test-Path $backendCertFile) { Copy-Item -Path $backendCertFile -Destination "$frontendSslDir/myp.crt" -Force } if (Test-Path $backendKeyFile) { Copy-Item -Path $backendKeyFile -Destination "$frontendSslDir/myp.key" -Force } Write-Host "Zertifikate ins Frontend-Verzeichnis kopiert." -ForegroundColor $ColorSuccess # Pruefen, ob .env.local existiert und aktualisieren $envLocalPath = "./frontend/.env.local" $envContent = "" if (Test-Path $envLocalPath) { $envContent = Get-Content -Path $envLocalPath -Raw } else { $envContent = "# MYP Frontend Umgebungsvariablen`n" } # SSL-Konfigurationen $sslConfigs = @( "NODE_TLS_REJECT_UNAUTHORIZED=0", "HTTPS=true", "SSL_CRT_FILE=./ssl/myp.crt", "SSL_KEY_FILE=./ssl/myp.key", "NEXT_PUBLIC_API_URL=https://$backendHostname", "NEXT_PUBLIC_BACKEND_HOST=$backendHostname", "NEXT_PUBLIC_BACKEND_PROTOCOL=https" ) # Existierende Konfigurationen aktualisieren foreach ($config in $sslConfigs) { $key = $config.Split('=')[0] $regex = "(?m)^$key=.*$" if ($envContent -match $regex) { # Update existierende Konfiguration $envContent = $envContent -replace $regex, $config } else { # Neue Konfiguration hinzufuegen $envContent += "`n$config" } } # Speichern der aktualisierten Umgebungsvariablen $envContent | Out-File -FilePath $envLocalPath -Encoding utf8 Write-Host ".env.local Datei mit SSL-Konfigurationen aktualisiert." -ForegroundColor $ColorSuccess } Write-Host "" Write-Host "SSL-Zertifikate wurden in folgenden Pfaden gespeichert:" -ForegroundColor $ColorInfo Write-Host "Backend: $backendCertFile" -ForegroundColor $ColorCommand Write-Host "Frontend: $frontendCertFile" -ForegroundColor $ColorCommand Write-Host "" Write-Host "Druecken Sie eine beliebige Taste, um fortzufahren..." $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } function Setup-Environment { Show-Header "Umgebungs-Setup" # Pruefen, ob Python und pip installiert sind $pythonInstalled = Test-CommandExists "python" $pipInstalled = Test-CommandExists "pip" if (-not $pythonInstalled -or -not $pipInstalled) { Write-Host "Python oder pip ist nicht installiert. Bitte installieren Sie Python 3.6+ und versuchen Sie es erneut." -ForegroundColor $ColorError Write-Host "" Write-Host "Druecken Sie eine beliebige Taste, um fortzufahren..." $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") return } # Python-Abhaengigkeiten installieren Write-Host "Installiere Backend-Abhaengigkeiten..." -ForegroundColor $ColorInfo Exec-Command "pip install -r backend/requirements.txt" "Installiere Python-Abhaengigkeiten" # Pruefen, ob Node.js und npm installiert sind $nodeInstalled = Test-CommandExists "node" $npmInstalled = Test-CommandExists "npm" if ($nodeInstalled -and $npmInstalled) { # Frontend-Abhaengigkeiten installieren Write-Host "Installiere Frontend-Abhaengigkeiten..." -ForegroundColor $ColorInfo Exec-Command "cd frontend && npm install" "Installiere Node.js-Abhaengigkeiten" } else { Write-Host "Node.js oder npm ist nicht installiert. Frontend-Abhaengigkeiten werden uebersprungen." -ForegroundColor $ColorWarning } # Docker-Compose Datei aktualisieren $dockerComposeFile = "docker-compose.yml" if (Test-Path $dockerComposeFile) { $dockerCompose = Get-Content $dockerComposeFile -Raw # Sicherstellen, dass dual-protocol aktiv ist if (-not $dockerCompose.Contains("--dual-protocol")) { $dockerCompose = $dockerCompose -replace "command: python -m app\.app", "command: python -m app.app --dual-protocol" $dockerCompose | Set-Content $dockerComposeFile Write-Host "Docker-Compose-Datei wurde aktualisiert, um den dual-protocol-Modus zu aktivieren." -ForegroundColor $ColorSuccess } else { Write-Host "Docker-Compose-Datei ist bereits korrekt konfiguriert." -ForegroundColor $ColorSuccess } } Write-Host "" Write-Host "Umgebungs-Setup abgeschlossen!" -ForegroundColor $ColorSuccess Write-Host "" Write-Host "Druecken Sie eine beliebige Taste, um fortzufahren..." $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } function Start-Application { Show-Header "Anwendung starten" Write-Host "Wie moechten Sie die Anwendung starten?" -ForegroundColor $ColorInfo Write-Host "1. Backend-Server starten (Python)" -ForegroundColor $ColorCommand Write-Host "2. Frontend-Server starten (Node.js)" -ForegroundColor $ColorCommand Write-Host "3. Beide Server starten (in separaten Fenstern)" -ForegroundColor $ColorCommand Write-Host "4. Mit Docker Compose starten" -ForegroundColor $ColorCommand Write-Host "5. Zurueck zum Hauptmenue" -ForegroundColor $ColorCommand $choice = Read-Host "Waehlen Sie eine Option (1-5)" if ($choice -eq "1") { Write-Host "Starte Backend-Server..." -ForegroundColor $ColorInfo Start-Process -FilePath "python" -ArgumentList "backend/app/app.py" -NoNewWindow Write-Host "Backend-Server laeuft jetzt im Hintergrund." -ForegroundColor $ColorSuccess } elseif ($choice -eq "2") { Write-Host "Starte Frontend-Server..." -ForegroundColor $ColorInfo Start-Process -FilePath "npm" -ArgumentList "run dev" -WorkingDirectory "frontend" -NoNewWindow Write-Host "Frontend-Server laeuft jetzt im Hintergrund." -ForegroundColor $ColorSuccess } elseif ($choice -eq "3") { Write-Host "Starte Backend-Server..." -ForegroundColor $ColorInfo Start-Process -FilePath "python" -ArgumentList "backend/app/app.py" -NoNewWindow Write-Host "Starte Frontend-Server..." -ForegroundColor $ColorInfo Start-Process -FilePath "npm" -ArgumentList "run dev" -WorkingDirectory "frontend" -NoNewWindow Write-Host "Beide Server laufen jetzt im Hintergrund." -ForegroundColor $ColorSuccess } elseif ($choice -eq "4") { $dockerInstalled = Test-CommandExists "docker" $dockerComposeInstalled = Test-CommandExists "docker-compose" if ($dockerInstalled -and $dockerComposeInstalled) { Write-Host "Starte Anwendung mit Docker Compose..." -ForegroundColor $ColorInfo Exec-Command "docker-compose up -d" "Starte Docker Container" Write-Host "Docker Container wurden gestartet." -ForegroundColor $ColorSuccess } else { Write-Host "Docker oder Docker Compose ist nicht installiert." -ForegroundColor $ColorError } } elseif ($choice -eq "5") { return } else { Write-Host "Ungueltige Option." -ForegroundColor $ColorError } Write-Host "" Write-Host "Druecken Sie eine beliebige Taste, um fortzufahren..." $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } # Hauptmenue anzeigen function Show-MainMenu { Show-Header "Hauptmenue" Write-Host "1. Systemvoraussetzungen pruefen" -ForegroundColor $ColorCommand Write-Host "2. Host-Konfiguration einrichten" -ForegroundColor $ColorCommand Write-Host "3. SSL-Zertifikate erstellen" -ForegroundColor $ColorCommand Write-Host "4. Umgebung einrichten (Abhaengigkeiten installieren)" -ForegroundColor $ColorCommand Write-Host "5. Anwendung starten" -ForegroundColor $ColorCommand Write-Host "6. Beenden" -ForegroundColor $ColorCommand Write-Host "" $choice = Read-Host "Waehlen Sie eine Option (1-6)" if ($choice -eq "1") { Test-Dependencies Show-MainMenu } elseif ($choice -eq "2") { Setup-Hosts Show-MainMenu } elseif ($choice -eq "3") { Create-SSLCertificates Show-MainMenu } elseif ($choice -eq "4") { Setup-Environment Show-MainMenu } elseif ($choice -eq "5") { Start-Application Show-MainMenu } elseif ($choice -eq "6") { exit } else { Write-Host "Ungueltige Option. Bitte versuchen Sie es erneut." -ForegroundColor $ColorError Start-Sleep -Seconds 2 Show-MainMenu } } # Skript starten Show-MainMenu