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

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

def main():
    handle = open(
        os.path.join(os.getenv("CYLC_WORKFLOW_RUN_DIR"), "log", "db"))
    lockf(handle, LOCK_SH)
    call([
        "cylc", "task-message", "I have locked the public database file"])
    workflow_log_dir = os.getenv("CYLC_WORKFLOW_LOG_DIR")
    while True:
        for line in open(os.path.join(workflow_log_dir, "log")):
            if "write attempt (1) did not complete" in line:
                return

if __name__ == "__main__":
    main()
