summaryrefslogtreecommitdiff
path: root/sumount.py
blob: db01d3eea425c347c71ce55b5208596c46bbc04d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python

import json
import os
import subprocess
import sys


def main():
    """Main entry point"""
    if len(sys.argv) != 2:
        sys.exit(f'Invalid parameter. Usage: {sys.argv[0]} <mapping>\n')

    cstm_error = ''

    try:
        cstm_error = 'Could not open config (~/.smount.json)'

        with open(os.path.expanduser('~/.smount.json')) as fp:
            config_dict = json.load(fp)

        cstm_error = 'Errror while executing all'

        if sys.argv[1].lower() == 'all':
            mounts = (
                subprocess.run(
                    [
                        '/bin/findmnt',
                        '-t',
                        'fuse.sshfs',
                        '--list',
                        '-n',
                        '-o',
                        'TARGET',
                    ],
                    capture_output=True,
                    check=False,
                    encoding='utf-8',
                )
                .stdout.strip()
                .split()
            )

            for key, value in config_dict.items():
                if value['dest'] not in mounts:
                    print(f'{key} not mounted')
                    continue

                subprocess.run(
                    ['/usr/bin/fusermount3', '-u', value['dest']], check=True
                )
                mounts.pop(mounts.index(value['dest']))
                print(f'umonted: {key} - {value["dest"]}')

            sys.exit(0)

        cstm_error = f'Invalid / nonexistent mapping: {sys.argv[1]}'
        data = config_dict[sys.argv[1]]
        subprocess.run(
            ['/usr/bin/fusermount3', '-u', data['dest']], check=True
        )
    except subprocess.CalledProcessError as err:
        print(f'Execution error: {err}', file=sys.stderr, flush=True)
    except Exception:
        print(f'Error: {cstm_error}', file=sys.stderr, flush=True)


if __name__ == '__main__':
    main()