start.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import os
  2. import subprocess
  3. import socket
  4. from pathlib import Path, PurePosixPath
  5. is_windows = os.name == "nt"
  6. def read_data_sources(hostname: str, login: str) -> list[Path]:
  7. file = Path(f"./data_sources_{hostname}_{login}")
  8. with open(file) as f:
  9. paths = f.readlines()
  10. return [Path(p_str.strip()).expanduser() for p_str in paths]
  11. def to_source_path(path: Path):
  12. mount_base = PurePosixPath("/mnt") / "source"
  13. inner_path = PurePosixPath(path)
  14. with_drive = PurePosixPath(inner_path.parts[0].replace(":", "")).joinpath(*inner_path.parts[1:])
  15. return mount_base / with_drive.relative_to(with_drive.anchor)
  16. def main():
  17. login = os.getlogin()
  18. hostname = socket.gethostname()
  19. data_sources = read_data_sources(hostname, login)
  20. container_name = "borgmatic"
  21. ssh_auth_sock = os.getenv("SSH_AUTH_SOCK")
  22. data_path = Path.cwd() / "data"
  23. config_d_path = data_path / "borgmatic.d"
  24. config_path = data_path / "borgmatic"
  25. credentials_path = data_path / "credentials"
  26. history_file = data_path / ".bash_history"
  27. history_file.touch()
  28. ssh_config_path = Path.home() / ".ssh"
  29. volumes = [
  30. f"{config_d_path}:/etc/borgmatic.d/",
  31. f"{config_path}:/etc/borgmatic/",
  32. f"{credentials_path}:/credentials/",
  33. f"{ssh_config_path}:/root/.ssh",
  34. f"{history_file}:/root/.bash_history",
  35. "borg_config:/root/.config/borg",
  36. "borg_cache:/root/.cache/borg",
  37. "borgmatic_state:/root/.local/state/borgmatic",
  38. ]
  39. if ssh_auth_sock:
  40. volumes += [f"{ssh_auth_sock}:{ssh_auth_sock}:Z"]
  41. volumes += [
  42. f"{vol}:{to_source_path(vol)}:ro" for vol in data_sources
  43. ]
  44. volume_args = [a for vol in volumes for a in ["-v", vol]]
  45. image_name = "ghcr.io/borgmatic-collective/borgmatic"
  46. args = [
  47. "podman",
  48. "run",
  49. "-h",
  50. hostname,
  51. "--detach",
  52. "--name",
  53. container_name,
  54. "-e",
  55. "SSH_AUTH_SOCK",
  56. "-e",
  57. "TZ=Europe/Paris",
  58. "-e",
  59. "SSH_KEY_NAME",
  60. "-e",
  61. f"HOST_LOGIN={login}",
  62. "--security-opt=label=disable"
  63. ] + volume_args + [image_name]
  64. print(args)
  65. subprocess.run(args)
  66. if __name__ == "__main__":
  67. main()