#!/usr/bin/env python3
"""Reconcile static CP publication only after matching application promotion."""
from pathlib import Path
import re
import subprocess

ci = Path('/home/dunedeploy/ci-deploy')
state = Path('/var/lib/dunerealms-ci-promote/deployed')
if not state.is_file():
    raise SystemExit(0)
sha = state.read_text().strip()
if not re.fullmatch('[0-9a-f]{40}', sha):
    raise SystemExit(1)
if any((ci / name).read_text().strip() != sha for name in ('built-commit', 'pending-commit')):
    raise SystemExit(0)
if Path('/home/dunerealms/apps/dunerealms/current').resolve().name != 'ci-' + sha:
    raise SystemExit(0)
subprocess.run(['systemctl', '--no-block', 'start', 'dunerealms-cpv2-preview.service'], check=True)
