
#!/usr/bin/env python3
"""
Proxmox Scripts Repository Generator
Version: 1.0.0
"""

from pathlib import Path
from zipfile import ZipFile, ZIP_DEFLATED
from datetime import date
import shutil

VERSION = "1.0.0"
TODAY = date.today().isoformat()

ROOT = Path("proxmox-scripts")
ZIP_NAME = f"proxmox-scripts-v{VERSION}.zip"
SOURCE_SCRIPT = Path("pve-qemu-install.sh")

README_FILES = {
    "README.md": """# Proxmox Scripts

A collection of installation, configuration and maintenance
scripts for Proxmox VE and related Linux systems.

## Repository structure

- `installation/` - Operating system and Proxmox installation
- `configuration/` - System configuration
- `maintenance/` - Maintenance and updates
- `monitoring/` - Monitoring tools
- `utilities/` - General-purpose utilities
- `templates/` - Reusable script templates

## Versioning

This repository uses Semantic Versioning (MAJOR.MINOR.PATCH).

## Requirements

- Debian-based Linux distribution unless stated otherwise
- Bash 4+
- Root privileges for system administration scripts

## Usage

Review every script before execution.

Make sure you understand its actions and requirements.

## License

MIT License. See LICENSE.
""",

    "installation/README.md": """# Installation

Scripts for installing operating systems and virtualization platforms.

Always check hardware compatibility and backups before installation.
""",

    "installation/proxmox/README.md": """# Proxmox VE Installation

Scripts specifically intended for Proxmox VE installation.

## Available scripts

### pve-qemu-install.sh

Version: 1.0.0

Launches the official Proxmox VE ISO using QEMU from a rescue system.

Features:
- Hardware virtualization check
- UEFI / Legacy boot detection
- Required package installation
- Physical disk selection
- Disk validation
- Proxmox ISO download
- QEMU launch with VNC access

**Warning:** The selected physical disks are passed directly to QEMU.
The Proxmox installer can erase all existing data on those disks.

Always verify disk selections before proceeding.
""",

    "installation/debian/README.md": """# Debian Installation

Scripts and documentation for Debian installation.

No installation scripts are currently included.
""",

    "configuration/README.md": """# Configuration

Scripts for configuring Linux and Proxmox systems.

Planned categories:
- Network
- Storage
- Services
""",

    "configuration/network/README.md": """# Network Configuration

Scripts for network interfaces, bridges, VLANs and network services.
""",

    "configuration/storage/README.md": """# Storage Configuration

Scripts for storage configuration, ZFS, disks and filesystems.

Always verify disk identifiers before making storage changes.
""",

    "configuration/services/README.md": """# Service Configuration

Scripts for configuring and managing system services.
""",

    "maintenance/README.md": """# Maintenance

Scripts for routine system administration and maintenance.
""",

    "maintenance/updates/README.md": """# Updates

Scripts for operating system and Proxmox updates.

Review release notes and backup important data before updating.
""",

    "maintenance/backup/README.md": """# Backup

Scripts for backup and recovery operations.
""",

    "maintenance/cleanup/README.md": """# Cleanup

Scripts for cleaning temporary files, logs and unused packages.
""",

    "monitoring/README.md": """# Monitoring

Scripts for system health, resource usage and monitoring.
""",

    "utilities/README.md": """# Utilities

General-purpose scripts and helper tools.
""",

    "templates/README.md": """# Templates

Reusable templates for new Bash scripts.

Copy script-template.sh when creating a new script.
Update its name, version and description.
""",

    "CHANGELOG.md": """# Changelog

All notable changes are documented here.

## [1.0.0] - 2026-12-01

### Added
- Initial repository structure
- Proxmox QEMU installer launcher
- Documentation for all categories
- Script template
- Repository ZIP generator
""",

    "LICENSE": """MIT License

Copyright (c) 2026 Proxmox Scripts Contributors

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files, to deal
in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
""",

    ".gitignore": """*.log
*.tmp
*.bak
*.swp
.DS_Store
__pycache__/
*.pyc
.env
""",

    "templates/script-template.sh": """#!/usr/bin/env bash
#
# Script       : script-name.sh
# Project      : Proxmox Scripts
# Version      : 1.0.0
# Date         : 2026-12-01
# Description  : Describe the purpose of this script.
#

set -Eeuo pipefail

SCRIPT_NAME="$(basename "$0")"
SCRIPT_VERSION="1.0.0"

info() {
    echo "[INFO] $*"
}

warn() {
    echo "[WARNING] $*" >&2
}

error() {
    echo "[ERROR] $*" >&2
    exit 1
}

if [[ $EUID -ne 0 ]]; then
    error "This script must be executed as root."
fi

info "$SCRIPT_NAME version $SCRIPT_VERSION"
info "Starting..."

# Your script starts here.

info "Finished."
"""
}


def create_repository():
    print("Creating Proxmox Scripts repository...")

    if ROOT.exists():
        shutil.rmtree(ROOT)

    ROOT.mkdir(parents=True)

    for filename, content in README_FILES.items():
        target = ROOT / filename
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(content.strip() + "\n", encoding="utf-8")

    # Import the existing QEMU installer
    if not SOURCE_SCRIPT.is_file():
        raise FileNotFoundError(
            f"Missing source script: {SOURCE_SCRIPT.resolve()}"
        )

    source = SOURCE_SCRIPT.read_text(encoding="utf-8")

    version_header = """#
# Script       : pve-qemu-install.sh
# Project      : Proxmox VE Installation
# Version      : 1.0.0
# Date         : 2026-12-01
# Description  : Launches the official Proxmox VE installer
#                using QEMU from a Hetzner Rescue System.
#
"""

    lines = source.splitlines()

    if any("Version      :" in line for line in lines[:15]):
        print("Existing version header detected; keeping source header.")
        updated_source = source
    elif lines and lines[0].startswith("#!"):
        updated_source = (
            lines[0] + "\n" +
            version_header +
            "\n".join(lines[1:]) + "\n"
        )
    else:
        updated_source = version_header + source

    installer = ROOT / "installation/proxmox/pve-qemu-install.sh"
    installer.write_text(updated_source, encoding="utf-8")
    installer.chmod(0o755)

    # Make the template executable
    template = ROOT / "templates/script-template.sh"
    template.chmod(0o755)

    print("Repository structure created.")


def create_zip():
    print(f"Creating {ZIP_NAME}...")

    with ZipFile(ZIP_NAME, "w", ZIP_DEFLATED) as archive:
        for path in ROOT.rglob("*"):
            if path.is_file():
                archive.write(path, path.as_posix())

    print("ZIP archive created successfully.")


if __name__ == "__main__":
    try:
        create_repository()
        create_zip()

        print()
        print("========================================")
        print(" Proxmox Scripts repository ready!")
        print("========================================")
        print(f"Repository : {ROOT.resolve()}")
        print(f"ZIP file   : {Path(ZIP_NAME).resolve()}")

    except Exception as exc:
        print(f"ERROR: {exc}")
        raise SystemExit(1)

