import argparse
import subprocess
import sys
from pathlib import Path
def main():
parser = argparse.ArgumentParser(
description="Configure systemd user service and timer for wallswitch."
)
parser.add_argument(
"-s", "--seconds",
type=int,
default=300,
help="Interval in seconds between wallpaper rotations (default: 300 / 5 minutes)."
)
args = parser.parse_args()
if args.seconds < 5:
print("Error: The interval must be at least 5 seconds.", file=sys.stderr)
sys.exit(1)
if args.seconds % 60 == 0:
desc_time = f"{args.seconds // 60} minutes"
else:
desc_time = f"{args.seconds} seconds"
print(f"Initializing systemd timer configuration (Interval: {desc_time})...")
home = Path.home()
cargo_bin = home / ".cargo" / "bin" / "wallswitch"
if not cargo_bin.exists():
print(f"Warning: Binary not found at {cargo_bin}")
print("Please ensure you have run 'cargo install --path=.' before triggering this script.")
systemd_user_dir = home / ".config" / "systemd" / "user"
service_path = systemd_user_dir / "wallswitch.service"
timer_path = systemd_user_dir / "wallswitch.timer"
systemd_user_dir.mkdir(parents=True, exist_ok=True)
service_content = f"""[Unit]
Description=Wallswitch Wallpaper Rotator
After=graphical-session.target
[Service]
Type=oneshot
ExecStart={cargo_bin} --once
"""
timer_content = f"""[Unit]
Description=Run Wallswitch every {desc_time}
[Timer]
OnActiveSec=0sec
OnUnitActiveSec={args.seconds}sec
AccuracySec=1s
[Install]
WantedBy=timers.target
"""
try:
service_path.write_text(service_content, encoding="utf-8")
print(f"Service file written to: {service_path}")
timer_path.write_text(timer_content, encoding="utf-8")
print(f"Timer file written to: {timer_path}")
print("Reloading systemd user daemon...")
subprocess.run(["systemctl", "--user", "daemon-reload"], check=True)
print("Enabling and starting wallswitch.timer...")
subprocess.run(
["systemctl", "--user", "enable", "--now", "wallswitch.timer"],
check=True
)
print("\nChecking systemd timer status:")
subprocess.run(
["systemctl", "--user", "status", "wallswitch.timer"],
check=False
)
print(f"\nSetup completed successfully! Wallswitch will run every {desc_time}.")
except subprocess.CalledProcessError as err:
print(f"\nError executing systemd commands: {err}", file=sys.stderr)
sys.exit(1)
except OSError as err:
print(f"\nFile system I/O error: {err}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()