#!/usr/bin/env python3

# This script waits on a named process to terminate before exiting. It will only wait if the process is present.

import os
import sys
import errno
import time
import subprocess

##
# @brief  Get the pid for the required process
# @param  name - process name
# @return pid of process or -1 if not found.
def get_pid(name):
    try:
        pid = subprocess.check_output(["pidof", name])
    except Exception as e:
        pid = -1
    return int(pid)

##
# @brief  Check if process pid is still active.
# @param  pid - process id
# @return True process is still running
def is_running(pid):
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            return False
    return True


##
# @brief  Wait for specified process to complete
# @param  argv - arguments
def main(argv=None):
    pid = get_pid(argv[1])
    if pid != -1:
        while is_running(pid):
            time.sleep(0.25)
    return


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: %s <process-name>" % os.path.basename(sys.argv[0]))
        sys.exit(1)
    sys.exit(main(sys.argv))
