#!/usr/bin/env python3 """Enterprise package builder for linux-backuper. Builds: 1. Pure Python Debian package (.deb) using standard ar / tar.gz formats. 2. RPM package (.rpm) via spec generation and rpmbuild (when available). 3. Universal binary distribution (.tar.gz) with standalone install.sh. Zero mandatory external pip dependencies required. """ import argparse import gzip import io import os import re import shutil import subprocess import sys import tarfile import time def get_version(repo_root: str) -> str: """Extract version from linux_backuper/__init__.py.""" init_path = os.path.join(repo_root, "linux_backuper", "__init__.py") with open(init_path, "r", encoding="utf-8") as f: content = f.read() match = re.search(r'__version__\s*=\s*["\']([^"\']+)["\']', content) if not match: raise ValueError("Could not find __version__ in linux_backuper/__init__.py") return match.group(1) def create_ar_archive(target_path: str, members: list): """Create a standard UNIX ar archive (Debian .deb package format). members is a list of tuples: (name: str, content: bytes, mode: int) """ with open(target_path, "wb") as out: # 8-byte ar magic header out.write(b"!\n") for name, data, mode in members: # Entry header format: # 0..15 (16) Name # 16..27 (12) Timestamp # 28..33 (6) Owner UID # 34..39 (6) Owner GID # 40..47 (8) File mode (octal) # 48..57 (10) File size (decimal) # 58..59 (2) Trailer `\x60\n` name_bytes = name.encode("ascii").ljust(16) timestamp_bytes = str(int(time.time())).encode("ascii").ljust(12) uid_bytes = b"0 " gid_bytes = b"0 " mode_bytes = f"{mode:o}".encode("ascii").ljust(8) size_bytes = str(len(data)).encode("ascii").ljust(10) trailer = b"`\n" header = ( name_bytes + timestamp_bytes + uid_bytes + gid_bytes + mode_bytes + size_bytes + trailer ) if len(header) != 60: raise ValueError(f"Malformed ar header length: {len(header)}") out.write(header) out.write(data) # ar entries are padded with \n if size is odd if len(data) % 2 != 0: out.write(b"\n") def build_deb_package(repo_root: str, out_dir: str, version: str) -> str: """Build a standard Debian .deb package in pure Python.""" deb_filename = f"linux-backuper_{version}_all.deb" deb_path = os.path.join(out_dir, deb_filename) os.makedirs(out_dir, exist_ok=True) # 1. debian-binary member debian_binary = b"2.0\n" # 2. control.tar.gz member control_content = f"""Package: linux-backuper Version: {version} Section: admin Priority: optional Architecture: all Depends: python3 (>= 3.6) Recommends: rsync, openssh-client Maintainer: wiredLAB Description: Enterprise Linux system snapshot and configuration backup utility. linux-backuper creates reliable, verifiable, and restorable system configuration and state snapshots across Debian, Ubuntu, RHEL, AlmaLinux, Fedora, and Arch Linux. Features include zero mandatory external pip dependencies, fast metadata indexing, live system diffing, dry-run safety restore, time-bucket retention pruning, and local-first remote synchronization. """ postinst_script = """#!/bin/sh set -e mkdir -p /var/backups/linux-backuper /etc/linux-backuper chmod 0700 /var/backups/linux-backuper exit 0 """ prerm_script = """#!/bin/sh set -e exit 0 """ control_buf = io.BytesIO() with tarfile.open(fileobj=control_buf, mode="w:gz", format=tarfile.PAX_FORMAT) as tar: # ./ ti = tarfile.TarInfo("./") ti.type = tarfile.DIRTYPE ti.mode = 0o755 ti.mtime = int(time.time()) tar.addfile(ti) # ./control data = control_content.encode("utf-8") ti = tarfile.TarInfo("./control") ti.size = len(data) ti.mode = 0o644 ti.mtime = int(time.time()) tar.addfile(ti, io.BytesIO(data)) # ./postinst data = postinst_script.encode("utf-8") ti = tarfile.TarInfo("./postinst") ti.size = len(data) ti.mode = 0o755 ti.mtime = int(time.time()) tar.addfile(ti, io.BytesIO(data)) # ./prerm data = prerm_script.encode("utf-8") ti = tarfile.TarInfo("./prerm") ti.size = len(data) ti.mode = 0o755 ti.mtime = int(time.time()) tar.addfile(ti, io.BytesIO(data)) control_tar_gz = control_buf.getvalue() # 3. data.tar.gz member data_buf = io.BytesIO() with tarfile.open(fileobj=data_buf, mode="w:gz", format=tarfile.PAX_FORMAT) as tar: def add_dir(path: str, mode: int = 0o755): ti = tarfile.TarInfo(path) ti.type = tarfile.DIRTYPE ti.mode = mode ti.mtime = int(time.time()) tar.addfile(ti) # Base directories add_dir("./usr") add_dir("./usr/bin") add_dir("./usr/lib") add_dir("./usr/lib/linux-backuper") add_dir("./etc") add_dir("./etc/linux-backuper") add_dir("./var") add_dir("./var/backups") add_dir("./var/backups/linux-backuper", mode=0o700) # Add executable /usr/bin/linux-backuper bin_src = os.path.join(repo_root, "bin", "linux-backuper") with open(bin_src, "rb") as f: bin_data = f.read() ti = tarfile.TarInfo("./usr/bin/linux-backuper") ti.size = len(bin_data) ti.mode = 0o755 ti.mtime = int(time.time()) tar.addfile(ti, io.BytesIO(bin_data)) # Add python library files to /usr/lib/linux-backuper/linux_backuper lib_src_root = os.path.join(repo_root, "linux_backuper") for root, dirs, files in os.walk(lib_src_root): dirs[:] = [d for d in dirs if d != "__pycache__" and not d.startswith("._")] rel_dir = os.path.relpath(root, repo_root) tar_dir = f"./usr/lib/linux-backuper/{rel_dir}".replace("\\", "/") add_dir(tar_dir) for file in sorted(files): if file.startswith("._") or file.endswith(".pyc") or file == "__pycache__": continue file_src = os.path.join(root, file) tar_file = f"{tar_dir}/{file}" with open(file_src, "rb") as f: file_data = f.read() ti = tarfile.TarInfo(tar_file) ti.size = len(file_data) ti.mode = 0o644 ti.mtime = int(time.time()) tar.addfile(ti, io.BytesIO(file_data)) # Add man page man_src = os.path.join(repo_root, "man", "linux-backuper.8") if os.path.isfile(man_src): add_dir("./usr/share") add_dir("./usr/share/man") add_dir("./usr/share/man/man8") with open(man_src, "rb") as f: man_raw = f.read() man_gz = gzip.compress(man_raw) ti = tarfile.TarInfo("./usr/share/man/man8/linux-backuper.8.gz") ti.size = len(man_gz) ti.mode = 0o644 ti.mtime = int(time.time()) tar.addfile(ti, io.BytesIO(man_gz)) # Add shell completions bash_comp_src = os.path.join(repo_root, "completions", "bash", "linux-backuper") if os.path.isfile(bash_comp_src): add_dir("./usr/share/bash-completion") add_dir("./usr/share/bash-completion/completions") with open(bash_comp_src, "rb") as f: comp_data = f.read() ti = tarfile.TarInfo("./usr/share/bash-completion/completions/linux-backuper") ti.size = len(comp_data) ti.mode = 0o644 ti.mtime = int(time.time()) tar.addfile(ti, io.BytesIO(comp_data)) zsh_comp_src = os.path.join(repo_root, "completions", "zsh", "_linux-backuper") if os.path.isfile(zsh_comp_src): add_dir("./usr/share/zsh") add_dir("./usr/share/zsh/site-functions") with open(zsh_comp_src, "rb") as f: comp_data = f.read() ti = tarfile.TarInfo("./usr/share/zsh/site-functions/_linux-backuper") ti.size = len(comp_data) ti.mode = 0o644 ti.mtime = int(time.time()) tar.addfile(ti, io.BytesIO(comp_data)) # Add documentation docs_src = os.path.join(repo_root, "docs") if os.path.isdir(docs_src): add_dir("./usr/share/doc") add_dir("./usr/share/doc/linux-backuper") for doc_name in ["user-guide.md", "admin-guide.md", "developer-guide.md"]: doc_path = os.path.join(docs_src, doc_name) if os.path.isfile(doc_path): with open(doc_path, "rb") as f: ddata = f.read() ti = tarfile.TarInfo(f"./usr/share/doc/linux-backuper/{doc_name}") ti.size = len(ddata) ti.mode = 0o644 ti.mtime = int(time.time()) tar.addfile(ti, io.BytesIO(ddata)) data_tar_gz = data_buf.getvalue() # Package into ar archive members = [ ("debian-binary", debian_binary, 0o644), ("control.tar.gz", control_tar_gz, 0o644), ("data.tar.gz", data_tar_gz, 0o644), ] create_ar_archive(deb_path, members) print(f"[SUCCESS] Built Debian package: {deb_path} ({os.path.getsize(deb_path)} bytes)") return deb_path def build_tar_package(repo_root: str, out_dir: str, version: str) -> str: """Build universal binary tarball distribution.""" tar_filename = f"linux-backuper-{version}.tar.gz" tar_path = os.path.join(out_dir, tar_filename) os.makedirs(out_dir, exist_ok=True) prefix = f"linux-backuper-{version}" with tarfile.open(tar_path, "w:gz", format=tarfile.PAX_FORMAT) as tar: # Add root dir ti = tarfile.TarInfo(prefix) ti.type = tarfile.DIRTYPE ti.mode = 0o755 tar.addfile(ti) # Add install script install_src = os.path.join(repo_root, "packaging", "install.sh") if os.path.isfile(install_src): with open(install_src, "rb") as f: data = f.read() ti = tarfile.TarInfo(f"{prefix}/install.sh") ti.size = len(data) ti.mode = 0o755 tar.addfile(ti, io.BytesIO(data)) # Add bin launcher bin_src = os.path.join(repo_root, "bin", "linux-backuper") with open(bin_src, "rb") as f: data = f.read() ti = tarfile.TarInfo(f"{prefix}/bin/linux-backuper") ti.size = len(data) ti.mode = 0o755 tar.addfile(ti, io.BytesIO(data)) # Add README readme_src = os.path.join(repo_root, "README.md") if os.path.isfile(readme_src): with open(readme_src, "rb") as f: data = f.read() ti = tarfile.TarInfo(f"{prefix}/README.md") ti.size = len(data) ti.mode = 0o644 tar.addfile(ti, io.BytesIO(data)) # Add python library lib_src_root = os.path.join(repo_root, "linux_backuper") for root, dirs, files in os.walk(lib_src_root): dirs[:] = [d for d in dirs if d != "__pycache__" and not d.startswith("._")] rel_dir = os.path.relpath(root, repo_root) tar_dir = f"{prefix}/{rel_dir}".replace("\\", "/") ti = tarfile.TarInfo(tar_dir) ti.type = tarfile.DIRTYPE ti.mode = 0o755 tar.addfile(ti) for file in sorted(files): if file.startswith("._") or file.endswith(".pyc") or file == "__pycache__": continue file_src = os.path.join(root, file) tar_file = f"{tar_dir}/{file}" with open(file_src, "rb") as f: data = f.read() ti = tarfile.TarInfo(tar_file) ti.size = len(data) ti.mode = 0o644 tar.addfile(ti, io.BytesIO(data)) # Add man page man_src = os.path.join(repo_root, "man", "linux-backuper.8") if os.path.isfile(man_src): with open(man_src, "rb") as f: data = f.read() ti = tarfile.TarInfo(f"{prefix}/man/linux-backuper.8") ti.size = len(data) ti.mode = 0o644 tar.addfile(ti, io.BytesIO(data)) # Add completions for shell, cname in [("bash", "linux-backuper"), ("zsh", "_linux-backuper")]: c_src = os.path.join(repo_root, "completions", shell, cname) if os.path.isfile(c_src): with open(c_src, "rb") as f: data = f.read() ti = tarfile.TarInfo(f"{prefix}/completions/{shell}/{cname}") ti.size = len(data) ti.mode = 0o644 tar.addfile(ti, io.BytesIO(data)) # Add docs docs_src = os.path.join(repo_root, "docs") if os.path.isdir(docs_src): for doc_name in ["user-guide.md", "admin-guide.md", "developer-guide.md"]: doc_path = os.path.join(docs_src, doc_name) if os.path.isfile(doc_path): with open(doc_path, "rb") as f: data = f.read() ti = tarfile.TarInfo(f"{prefix}/docs/{doc_name}") ti.size = len(data) ti.mode = 0o644 tar.addfile(ti, io.BytesIO(data)) print(f"[SUCCESS] Built binary tarball: {tar_path} ({os.path.getsize(tar_path)} bytes)") return tar_path def generate_rpm_spec(repo_root: str, out_dir: str, version: str) -> str: """Generate standard RPM .spec file for building .rpm packages.""" spec_content = f"""Name: linux-backuper Version: {version} Release: 1%{{?dist}} Summary: Enterprise Linux system snapshot and configuration backup utility License: MIT URL: https://gitea.wired.synology.me/soda64/linux-backuper Source0: linux-backuper-%{{version}}.tar.gz BuildArch: noarch Requires: python3 >= 3.6 Recommends: rsync, openssh-clients %description linux-backuper is an enterprise-grade Linux system snapshot and configuration backup utility written in pure Python >= 3.6 with zero mandatory external pip dependencies. It features fast manifest indexing, live system diffing, safe restore with dry-run protection, time-bucket pruning, and local-first remote storage synchronization. %prep %setup -q %build # Pure python, no compile step needed %install rm -rf %{{buildroot}} mkdir -p %{{buildroot}}/usr/bin mkdir -p %{{buildroot}}/usr/lib/linux-backuper/linux_backuper mkdir -p %{{buildroot}}/etc/linux-backuper mkdir -p %{{buildroot}}/var/backups/linux-backuper cp -r bin/linux-backuper %{{buildroot}}/usr/bin/linux-backuper chmod 0755 %{{buildroot}}/usr/bin/linux-backuper cp -r linux_backuper/* %{{buildroot}}/usr/lib/linux-backuper/linux_backuper/ find %{{buildroot}}/usr/lib/linux-backuper -name "._*" -delete find %{{buildroot}}/usr/lib/linux-backuper -name "__pycache__" -type d -exec rm -rf {{}} + 2>/dev/null || true find %{{buildroot}}/usr/lib/linux-backuper -type d -exec chmod 0755 {{}} + find %{{buildroot}}/usr/lib/linux-backuper -type f -exec chmod 0644 {{}} + if [ -f man/linux-backuper.8 ]; then mkdir -p %{{buildroot}}%{{_mandir}}/man8 gzip -c -n man/linux-backuper.8 > %{{buildroot}}%{{_mandir}}/man8/linux-backuper.8.gz chmod 0644 %{{buildroot}}%{{_mandir}}/man8/linux-backuper.8.gz fi if [ -f completions/bash/linux-backuper ]; then mkdir -p %{{buildroot}}/usr/share/bash-completion/completions cp completions/bash/linux-backuper %{{buildroot}}/usr/share/bash-completion/completions/linux-backuper chmod 0644 %{{buildroot}}/usr/share/bash-completion/completions/linux-backuper fi if [ -f completions/zsh/_linux-backuper ]; then mkdir -p %{{buildroot}}/usr/share/zsh/site-functions cp completions/zsh/_linux-backuper %{{buildroot}}/usr/share/zsh/site-functions/_linux-backuper chmod 0644 %{{buildroot}}/usr/share/zsh/site-functions/_linux-backuper fi if [ -d docs ]; then mkdir -p %{{buildroot}}/usr/share/doc/linux-backuper cp docs/*.md %{{buildroot}}/usr/share/doc/linux-backuper/ 2>/dev/null || true chmod 0644 %{{buildroot}}/usr/share/doc/linux-backuper/* 2>/dev/null || true fi %files %defattr(-,root,root,-) /usr/bin/linux-backuper /usr/lib/linux-backuper %dir /etc/linux-backuper %attr(0700,root,root) %dir /var/backups/linux-backuper %{{_mandir}}/man8/linux-backuper.8* /usr/share/bash-completion/completions/linux-backuper /usr/share/zsh/site-functions/_linux-backuper /usr/share/doc/linux-backuper %changelog * Fri Oct 09 2026 wiredLAB - {version}-1 - Initial release of linux-backuper. """ spec_path = os.path.join(out_dir, "linux-backuper.spec") with open(spec_path, "w", encoding="utf-8") as f: f.write(spec_content) print(f"[SUCCESS] Generated RPM spec: {spec_path}") return spec_path def build_rpm_package(repo_root: str, out_dir: str, version: str) -> str: """Build RPM package using rpmbuild if available.""" spec_path = generate_rpm_spec(repo_root, out_dir, version) rpmbuild_bin = shutil.which("rpmbuild") if not rpmbuild_bin: print("[WARNING] 'rpmbuild' binary not found on this system. RPM spec was generated, but .rpm build skipped.") return spec_path # Build source tarball required by rpmbuild tar_path = build_tar_package(repo_root, out_dir, version) # Set up isolated rpmbuild directory structure inside out_dir/rpmbuild rpmbuild_dir = os.path.abspath(os.path.join(out_dir, "rpmbuild")) for d in ["BUILD", "RPMS", "SOURCES", "SPECS", "SRPMS"]: os.makedirs(os.path.join(rpmbuild_dir, d), exist_ok=True) # Copy source tarball to SOURCES and spec to SPECS shutil.copy2(tar_path, os.path.join(rpmbuild_dir, "SOURCES")) rpm_spec_in_tree = os.path.join(rpmbuild_dir, "SPECS", "linux-backuper.spec") shutil.copy2(spec_path, rpm_spec_in_tree) cmd = [ rpmbuild_bin, "-bb", f"--define=_topdir {rpmbuild_dir}", rpm_spec_in_tree, ] print(f"[INFO] Running rpmbuild: {' '.join(cmd)}") result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) if result.returncode != 0: print(f"[ERROR] rpmbuild failed:\n{result.stderr}", file=sys.stderr) raise RuntimeError("rpmbuild execution failed") # Locate generated rpm and copy to out_dir rpms_found = [] for root, _, files in os.walk(os.path.join(rpmbuild_dir, "RPMS")): for f in files: if f.endswith(".rpm"): full_rpm = os.path.join(root, f) target_rpm = os.path.join(out_dir, f) shutil.copy2(full_rpm, target_rpm) rpms_found.append(target_rpm) if not rpms_found: raise RuntimeError("rpmbuild succeeded but no .rpm file was found in RPMS") # Clean up temporary rpmbuild staging tree so out_dir contains only final artifacts shutil.rmtree(rpmbuild_dir, ignore_errors=True) print(f"[SUCCESS] Built RPM package: {rpms_found[0]} ({os.path.getsize(rpms_found[0])} bytes)") return rpms_found[0] def main(): parser = argparse.ArgumentParser(description="Package builder for linux-backuper") parser.add_argument("--deb", action="store_true", help="Build Debian .deb package") parser.add_argument("--rpm", action="store_true", help="Build RPM .rpm package / spec") parser.add_argument("--tar", action="store_true", help="Build universal .tar.gz package") parser.add_argument("--all", action="store_true", help="Build all package types (default)") parser.add_argument("--out-dir", default="dist", help="Output directory (default: dist)") args = parser.parse_args() repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) version = get_version(repo_root) out_dir = os.path.abspath(args.out_dir) build_all = args.all or (not args.deb and not args.rpm and not args.tar) print(f"[INFO] Building packages for linux-backuper v{version} into {out_dir}") if build_all or args.tar: build_tar_package(repo_root, out_dir, version) if build_all or args.deb: build_deb_package(repo_root, out_dir, version) if build_all or args.rpm: build_rpm_package(repo_root, out_dir, version) if __name__ == "__main__": main()