#!/usr/bin/env python3
"""Lock a suite's database file."""

from fcntl import lockf, LOCK_SH
import os
import time
from subprocess import call

def main():
    handle = open(
        os.path.join(os.getenv("CYLC_SUITE_RUN_DIR"), "log", "db"))
    lockf(handle, LOCK_SH)
    call([
        "cylc", "task", "message", "I have locked the public database file"])
    suite_log_dir = os.getenv("CYLC_SUITE_LOG_DIR")
    while True:
        for line in open(os.path.join(suite_log_dir, "log")):
            if "db: recovered from" in line:
                return
        time.sleep(1)

if __name__ == "__main__":
    main()
