Copy #!/usr/bin/env python3
"""
Phoenix Cross-Platform Deployment Script
Generated: 2025-07-13
Agent: Phoenix (System Deployment & Containerization Specialist)
"""
import os
import sys
import json
import platform
import subprocess
import argparse
from pathlib import Path
from typing import Dict, List, Optional
from datetime import datetime
# Script metadata
SCRIPT_VERSION = "1.0.0"
GENERATED_DATE = "2025-07-13"
AGENT = "Phoenix"
class PlatformDetector:
"""Intelligent platform detection and capability assessment."""
@staticmethod
def detect_platform() -> Dict[str, str]:
"""Detect current platform details."""
system = platform.system().lower()
machine = platform.machine().lower()
# Normalize architecture names
arch_map = {
'x86_64': 'amd64',
'amd64': 'amd64',
'arm64': 'arm64',
'aarch64': 'arm64',
'armv7l': 'arm32'
}
arch = arch_map.get(machine, machine)
# Detect distribution for Linux
distro = ""
if system == "linux":
try:
with open("/etc/os-release", "r") as f:
for line in f:
if line.startswith("ID="):
distro = line.split("=")[1].strip().strip('"')
break
except FileNotFoundError:
distro = "unknown"
elif system == "darwin":
distro = "macos"
elif system == "windows":
distro = "windows"
return {
"system": system,
"architecture": arch,
"distribution": distro,
"platform_string": f"{system}-{arch}-{distro}",
"python_version": platform.python_version(),
"detection_date": datetime.now().isoformat()
}
class DependencyManager:
"""Cross-platform dependency management."""
def __init__(self, platform_info: Dict[str, str]):
self.platform = platform_info
def install_dependencies(self, skip: bool = False) -> bool:
"""Install platform-specific dependencies."""
if skip:
print("βοΈ Skipping dependency installation")
return True
print("π¦ Installing dependencies...")
system = self.platform["system"]
distro = self.platform["distribution"]
try:
if system == "linux":
if distro in ["ubuntu", "debian"]:
self._run_command(["sudo", "apt-get", "update"])
self._run_command(["sudo", "apt-get", "install", "-y", "docker.io", "git", "curl"])
elif distro in ["centos", "rhel", "fedora"]:
self._run_command(["sudo", "yum", "install", "-y", "docker", "git", "curl"])
else:
print(f"β οΈ Unknown Linux distribution: {distro}")
return False
elif system == "darwin":
if self._command_exists("brew"):
self._run_command(["brew", "install", "docker", "git"])
else:
print("β Homebrew not found. Please install manually.")
return False
elif system == "windows":
if self._command_exists("winget"):
self._run_command(["winget", "install", "--id", "Docker.DockerDesktop"])
self._run_command(["winget", "install", "--id", "Git.Git"])
elif self._command_exists("choco"):
self._run_command(["choco", "install", "docker-desktop", "git", "-y"])
else:
print("β No package manager found. Please install manually.")
return False
print("β
Dependencies installed successfully")
return True
except subprocess.CalledProcessError as e:
print(f"β Dependency installation failed: {e}")
return False
def _command_exists(self, command: str) -> bool:
"""Check if a command exists in PATH."""
try:
subprocess.run([command, "--version"],
capture_output=True, check=True)
return True
except (subprocess.CalledProcessError, FileNotFoundError):
return False
def _run_command(self, command: List[str]) -> subprocess.CompletedProcess:
"""Run a command with error handling."""
print(f"π§ Running: {' '.join(command)}")
return subprocess.run(command, check=True)
class ConfigurationManager:
"""Environment configuration management."""
def __init__(self, config_path: Path):
self.config_path = config_path
def load_configuration(self, environment: str) -> Dict[str, str]:
"""Load environment-specific configuration."""
config_file = self.config_path / f"{environment}.json"
if not config_file.exists():
print(f"β οΈ Configuration file not found: {config_file}")
return {}
try:
with open(config_file, "r") as f:
config = json.load(f)
print(f"βοΈ Loaded configuration for environment: {environment}")
# Set environment variables
for key, value in config.items():
os.environ[key] = str(value)
print(f"π§ Set {key}={value}")
return config
except (json.JSONDecodeError, IOError) as e:
print(f"β Failed to load configuration: {e}")
return {}
class HealthChecker:
"""System health validation."""
def __init__(self):
self.checks = [
("Docker", ["docker", "--version"]),
("Git", ["git", "--version"]),
("Python", ["python3", "--version"]),
("Curl", ["curl", "--version"])
]
def run_health_checks(self) -> bool:
"""Run comprehensive health checks."""
print("π₯ Running health checks...")
all_passed = True
for name, command in self.checks:
try:
subprocess.run(command, capture_output=True, check=True)
print(f"β
{name} check passed")
except (subprocess.CalledProcessError, FileNotFoundError):
print(f"β {name} check failed")
all_passed = False
# Network connectivity check
try:
subprocess.run(["curl", "-s", "https://google.com"],
capture_output=True, check=True, timeout=10)
print("β
Network connectivity check passed")
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
print("β Network connectivity check failed")
all_passed = False
return all_passed
def main():
"""Main deployment script execution."""
parser = argparse.ArgumentParser(description="Phoenix Cross-Platform Deployment Script")
parser.add_argument("--environment", "-e", default="production",
help="Deployment environment (default: production)")
parser.add_argument("--config-path", "-c", default="./config",
help="Configuration directory path (default: ./config)")
parser.add_argument("--skip-dependencies", "-s", action="store_true",
help="Skip dependency installation")
args = parser.parse_args()
print(f"π₯ Phoenix Deployment Script v{SCRIPT_VERSION}")
print(f"π
Generated: {GENERATED_DATE}")
print(f"π Environment: {args.environment}")
print(f"π Config Path: {args.config_path}")
print()
try:
# Platform detection
detector = PlatformDetector()
platform_info = detector.detect_platform()
print(f"π₯οΈ Platform: {platform_info['platform_string']}")
print(f"π Python: {platform_info['python_version']}")
print()
# Dependency installation
dep_manager = DependencyManager(platform_info)
if not dep_manager.install_dependencies(args.skip_dependencies):
sys.exit(1)
# Configuration management
config_manager = ConfigurationManager(Path(args.config_path))
config = config_manager.load_configuration(args.environment)
# Health checks
health_checker = HealthChecker()
if not health_checker.run_health_checks():
print("β οΈ Some health checks failed, but continuing...")
print()
print("π Deployment preparation completed successfully!")
except KeyboardInterrupt:
print("\nβΉοΈ Deployment interrupted by user")
sys.exit(1)
except Exception as e:
print(f"\nπ₯ Deployment failed: {e}")
sys.exit(1)
if __name__ == "__main__":
main()