Projektarbeit-MYP/myp_installer.ps1

518 lines
19 KiB
PowerShell

# MYP Installer Control Center
# Zentrale Installationskonsole für die MYP-Plattform
# Kombiniert Setup-Funktionen für SSL, Hosts, Docker und mehr
# Farbdefinitionen für bessere Lesbarkeit
$colors = @{
Title = "Cyan"
Success = "Green"
Error = "Red"
Warning = "Yellow"
Info = "Blue"
Command = "White"
}
# Überprüfen, ob das Skript als Administrator ausgeführt 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 $colors.Title
Write-Host " MYP INSTALLER CONTROL CENTER" -ForegroundColor $colors.Title
Write-Host "=============================================================" -ForegroundColor $colors.Title
Write-Host " $Title" -ForegroundColor $colors.Title
Write-Host "=============================================================" -ForegroundColor $colors.Title
if (-not $isAdmin) {
Write-Host "HINWEIS: Dieses Skript läuft ohne Administrator-Rechte." -ForegroundColor $colors.Warning
Write-Host "Einige Funktionen sind möglicherweise eingeschränkt." -ForegroundColor $colors.Warning
Write-Host "=============================================================" -ForegroundColor $colors.Title
}
Write-Host ""
}
function Test-Command {
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 $colors.Info
try {
Invoke-Expression $Command | Out-Host
if ($LASTEXITCODE -eq 0 -or $null -eq $LASTEXITCODE) {
Write-Host "✓ Erfolgreich abgeschlossen!" -ForegroundColor $colors.Success
return $true
} else {
Write-Host "✗ Fehler beim Ausführen des Befehls. Exit-Code: $LASTEXITCODE" -ForegroundColor $colors.Error
return $false
}
} catch {
Write-Host "✗ Fehler: $_" -ForegroundColor $colors.Error
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 {
Write-Host "Prüfe Abhängigkeiten..." -ForegroundColor $colors.Info
$dependencies = @{
"python" = "Python (3.6+)"
"pip" = "Python Package Manager"
"docker" = "Docker"
"docker-compose" = "Docker Compose"
"node" = "Node.js"
"npm" = "Node Package Manager"
"openssl" = "OpenSSL"
}
$allInstalled = $true
foreach ($dep in $dependencies.GetEnumerator()) {
$installed = Test-Command $dep.Key
if ($installed) {
Write-Host "$($dep.Value) gefunden" -ForegroundColor $colors.Success
} else {
Write-Host "$($dep.Value) nicht gefunden" -ForegroundColor $colors.Error
$allInstalled = $false
}
}
return $allInstalled
}
function Setup-Hosts {
Show-Header "Host-Konfiguration"
if (-not $isAdmin) {
Write-Host "Diese Funktion erfordert Administrator-Rechte." -ForegroundColor $colors.Error
Write-Host "Bitte starten Sie das Skript als Administrator neu." -ForegroundColor $colors.Warning
return
}
$localIP = Get-LocalIPAddress
Write-Host "Lokale IP-Adresse: $localIP" -ForegroundColor $colors.Success
$hostsFile = "$env:windir\System32\drivers\etc\hosts"
Write-Host "Hosts-Datei: $hostsFile" -ForegroundColor $colors.Info
# Prüfen, ob die Einträge bereits existieren
$frontendEntry = Select-String -Path $hostsFile -Pattern "m040tbaraspi001.de040.corpintra.net" -Quiet
$backendEntry = Select-String -Path $hostsFile -Pattern "raspberrypi" -Quiet
# Einträge in die Hosts-Datei schreiben
Write-Host "Aktualisiere Hosts-Datei..." -ForegroundColor $colors.Info
$hostsContent = Get-Content -Path $hostsFile
if (-not $frontendEntry) {
$hostsContent += ""
$hostsContent += "# MYP Frontend Host"
$hostsContent += "$localIP m040tbaraspi001.de040.corpintra.net m040tbaraspi001"
Write-Host "Frontend-Hostname hinzugefügt" -ForegroundColor $colors.Success
} else {
Write-Host "Frontend-Hostname ist bereits konfiguriert" -ForegroundColor $colors.Warning
}
if (-not $backendEntry) {
$hostsContent += ""
$hostsContent += "# MYP Backend Host"
$hostsContent += "$localIP raspberrypi"
Write-Host "Backend-Hostname hinzugefügt" -ForegroundColor $colors.Success
} else {
Write-Host "Backend-Hostname ist bereits konfiguriert" -ForegroundColor $colors.Warning
}
# Speichern der aktualisierten Hosts-Datei
try {
$hostsContent | Set-Content -Path $hostsFile -Force
Write-Host "Konfiguration abgeschlossen!" -ForegroundColor $colors.Success
} catch {
Write-Host "Fehler beim Schreiben der Hosts-Datei: $_" -ForegroundColor $colors.Error
}
Write-Host ""
Write-Host "Folgende Hostnamen sind jetzt konfiguriert:" -ForegroundColor $colors.Info
Write-Host " - Frontend: m040tbaraspi001.de040.corpintra.net" -ForegroundColor $colors.Command
Write-Host " - Backend: raspberrypi" -ForegroundColor $colors.Command
Write-Host ""
Write-Host "Drücken 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 für folgende Hostnamen erstellt:" -ForegroundColor $colors.Info
# Hostname-Auswahl
Write-Host "1. Für lokale Entwicklung (localhost)" -ForegroundColor $colors.Command
Write-Host "2. Für Raspberry Pi Deployment (raspberrypi)" -ForegroundColor $colors.Command
Write-Host "3. Für Unternehmens-Setup (m040tbaraspi001.de040.corpintra.net)" -ForegroundColor $colors.Command
$choice = Read-Host "Wählen Sie eine Option (1-3, Standard: 1)"
switch ($choice) {
"2" {
$backendHostname = "raspberrypi"
$frontendHostname = "raspberrypi"
}
"3" {
$backendHostname = "raspberrypi"
$frontendHostname = "m040tbaraspi001.de040.corpintra.net"
}
default {
$backendHostname = "localhost"
$frontendHostname = "localhost"
}
}
Write-Host "Backend-Hostname: $backendHostname" -ForegroundColor $colors.Info
Write-Host "Frontend-Hostname: $frontendHostname" -ForegroundColor $colors.Info
Write-Host ""
# Verzeichnis erstellen, falls es nicht existiert
if (!(Test-Path $certDir)) {
Write-Host "Erstelle Verzeichnis $certDir..." -ForegroundColor $colors.Info
New-Item -ItemType Directory -Path $certDir -Force | Out-Null
}
# SSL-Zertifikate mit Python und cryptography erstellen
Write-Host "Erstelle SSL-Zertifikate mit Python..." -ForegroundColor $colors.Info
$pythonInstalled = Test-Command "python"
if ($pythonInstalled) {
# Überprüfen, 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-Abhängigkeit 'cryptography'..." -ForegroundColor $colors.Warning
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 Schlüssel generieren
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=4096,
)
# Schlüsseldatei 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 gültig
# Name für 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 für '{hostname}' erstellt:")
print(f"Zertifikat: {cert_path}")
print(f"Schlüssel: {key_path}")
print(f"Gültig für 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 ausführen
try {
python $tempScriptPath
Write-Host "SSL-Zertifikate erfolgreich erstellt!" -ForegroundColor $colors.Success
} catch {
Write-Host "Fehler beim Erstellen der SSL-Zertifikate: $_" -ForegroundColor $colors.Error
} finally {
# Temporäres Skript löschen
Remove-Item -Path $tempScriptPath -Force
}
} else {
Write-Host "Python nicht gefunden. SSL-Zertifikate können nicht erstellt werden." -ForegroundColor $colors.Error
}
# Zertifikate im System installieren (optional)
if ($isAdmin) {
$installCerts = Read-Host "Möchten Sie die Zertifikate im System installieren? (j/n, Standard: n)"
if ($installCerts -eq "j") {
if (Test-Path $backendCertFile) {
Write-Host "Installiere Backend-Zertifikat im System..." -ForegroundColor $colors.Info
Exec-Command "certutil -addstore -f 'ROOT' '$backendCertFile'" "Installiere im Root-Zertifikatsspeicher"
}
if (Test-Path $frontendCertFile) {
Write-Host "Installiere Frontend-Zertifikat im System..." -ForegroundColor $colors.Info
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 $colors.Warning
}
Write-Host ""
Write-Host "SSL-Zertifikate wurden in folgenden Pfaden gespeichert:" -ForegroundColor $colors.Info
Write-Host "Backend: $backendCertFile" -ForegroundColor $colors.Command
Write-Host "Frontend: $frontendCertFile" -ForegroundColor $colors.Command
Write-Host ""
Write-Host "Drücken Sie eine beliebige Taste, um fortzufahren..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
function Setup-Environment {
Show-Header "Umgebungs-Setup"
# Prüfen, ob Python und pip installiert sind
$pythonInstalled = Test-Command "python"
$pipInstalled = Test-Command "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 $colors.Error
return
}
# Python-Abhängigkeiten installieren
Write-Host "Installiere Backend-Abhängigkeiten..." -ForegroundColor $colors.Info
Exec-Command "pip install -r backend/requirements.txt" "Installiere Python-Abhängigkeiten"
# Prüfen, ob Node.js und npm installiert sind
$nodeInstalled = Test-Command "node"
$npmInstalled = Test-Command "npm"
if ($nodeInstalled -and $npmInstalled) {
# Frontend-Abhängigkeiten installieren
Write-Host "Installiere Frontend-Abhängigkeiten..." -ForegroundColor $colors.Info
Exec-Command "cd frontend && npm install" "Installiere Node.js-Abhängigkeiten"
} else {
Write-Host "Node.js oder npm ist nicht installiert. Frontend-Abhängigkeiten werden übersprungen." -ForegroundColor $colors.Warning
}
Write-Host ""
Write-Host "Umgebungs-Setup abgeschlossen!" -ForegroundColor $colors.Success
Write-Host ""
Write-Host "Drücken Sie eine beliebige Taste, um fortzufahren..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
function Start-Application {
Show-Header "Anwendung starten"
Write-Host "Wie möchten Sie die Anwendung starten?" -ForegroundColor $colors.Info
Write-Host "1. Backend-Server starten (Python)" -ForegroundColor $colors.Command
Write-Host "2. Frontend-Server starten (Node.js)" -ForegroundColor $colors.Command
Write-Host "3. Beide Server starten (in separaten Fenstern)" -ForegroundColor $colors.Command
Write-Host "4. Mit Docker Compose starten" -ForegroundColor $colors.Command
Write-Host "5. Zurück zum Hauptmenü" -ForegroundColor $colors.Command
$choice = Read-Host "Wählen Sie eine Option (1-5)"
switch ($choice) {
"1" {
Write-Host "Starte Backend-Server..." -ForegroundColor $colors.Info
Start-Process -FilePath "python" -ArgumentList "backend/app/app.py" -NoNewWindow
Write-Host "Backend-Server läuft jetzt im Hintergrund." -ForegroundColor $colors.Success
}
"2" {
Write-Host "Starte Frontend-Server..." -ForegroundColor $colors.Info
Start-Process -FilePath "npm" -ArgumentList "run dev" -WorkingDirectory "frontend" -NoNewWindow
Write-Host "Frontend-Server läuft jetzt im Hintergrund." -ForegroundColor $colors.Success
}
"3" {
Write-Host "Starte Backend-Server..." -ForegroundColor $colors.Info
Start-Process -FilePath "python" -ArgumentList "backend/app/app.py" -NoNewWindow
Write-Host "Starte Frontend-Server..." -ForegroundColor $colors.Info
Start-Process -FilePath "npm" -ArgumentList "run dev" -WorkingDirectory "frontend" -NoNewWindow
Write-Host "Beide Server laufen jetzt im Hintergrund." -ForegroundColor $colors.Success
}
"4" {
$dockerInstalled = Test-Command "docker"
$dockerComposeInstalled = Test-Command "docker-compose"
if ($dockerInstalled -and $dockerComposeInstalled) {
Write-Host "Starte Anwendung mit Docker Compose..." -ForegroundColor $colors.Info
Exec-Command "docker-compose up -d" "Starte Docker Container"
Write-Host "Docker Container wurden gestartet." -ForegroundColor $colors.Success
} else {
Write-Host "Docker oder Docker Compose ist nicht installiert." -ForegroundColor $colors.Error
}
}
"5" {
return
}
default {
Write-Host "Ungültige Option." -ForegroundColor $colors.Error
}
}
Write-Host ""
Write-Host "Drücken Sie eine beliebige Taste, um fortzufahren..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
# Hauptmenü anzeigen
function Show-MainMenu {
Show-Header "Hauptmenü"
Write-Host "1. Systemvoraussetzungen prüfen" -ForegroundColor $colors.Command
Write-Host "2. Host-Konfiguration einrichten" -ForegroundColor $colors.Command
Write-Host "3. SSL-Zertifikate erstellen" -ForegroundColor $colors.Command
Write-Host "4. Umgebung einrichten (Abhängigkeiten installieren)" -ForegroundColor $colors.Command
Write-Host "5. Anwendung starten" -ForegroundColor $colors.Command
Write-Host "Q. Beenden" -ForegroundColor $colors.Command
Write-Host ""
Write-Host "Wählen Sie eine Option (1-5, Q): " -ForegroundColor $colors.Info -NoNewline
$choice = Read-Host
switch ($choice) {
"1" {
Test-Dependencies
Write-Host ""
Write-Host "Drücken Sie eine beliebige Taste, um fortzufahren..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Show-MainMenu
}
"2" {
Setup-Hosts
Show-MainMenu
}
"3" {
Create-SSLCertificates
Show-MainMenu
}
"4" {
Setup-Environment
Show-MainMenu
}
"5" {
Start-Application
Show-MainMenu
}
"Q" {
exit
}
"q" {
exit
}
default {
Write-Host "Ungültige Option. Bitte versuchen Sie es erneut." -ForegroundColor $colors.Error
Start-Sleep -Seconds 2
Show-MainMenu
}
}
}
# Skript starten
Show-MainMenu