#!/usr/bin/python3

import sys
import time
import json
import subprocess
from hook_invoker_lib.hook import print_err, args_volume_type_paser

def find_mounted_ecryptfs(volume):
    try:
        output = subprocess.check_output(['findmnt', '-t', 'ecryptfs', '--json']).decode('utf-8')
        result = json.loads(output)

        ecryptfs_mounts = []
        for fs in result['filesystems']:
            if fs['target'].startswith(volume):
                ecryptfs_mounts.append(fs['target'])
                
        return ecryptfs_mounts
    
    except subprocess.CalledProcessError as e:
        print_err('find mounted ecryptfs failed')
        return []

def umount_ecryptfs(mount_points):
    for mount_point in mount_points:
        try:
            subprocess.check_call(['umount', mount_point])
        except subprocess.CalledProcessError as e:
            print_err('umount {} failed'.format(mount_point))

if __name__ == "__main__":
    volumes, _ = args_volume_type_paser()

    if len(volumes) == 0:
        sys.exit(0)

    for volume in volumes:
        ecryptfs_mounts = find_mounted_ecryptfs(volume)
        if len(ecryptfs_mounts) == 0:
            continue

        umount_ecryptfs(ecryptfs_mounts)

    sys.exit(0)