#!/usr/bin/env python3

import argparse
import subprocess
import sys
import time


def safe_umount(path):
    retry_count = 10
    not_mounted_str = 'umount: {}: not mounted'.format(path)

    last_code = 0
    while retry_count:
        proc = subprocess.Popen(['mountpoint', '-q', path])
        proc.wait()
        if proc.returncode:
            return 0

        proc = subprocess.Popen(['umount', path], stderr=subprocess.PIPE)
        (stdout, stderr) = proc.communicate()
        if not proc.returncode:
            return 0

        error = stderr.strip()
        if error == not_mounted_str:
            return 0

        retry_count -= 1
        last_code = proc.returncode
        time.sleep(0.500)
    return last_code


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('path')
    args = parser.parse_args()
    sys.exit(safe_umount(args.path))
