#!/opt/cloudlinux/venv/bin/python3 -bb
#coding:utf-8

# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import subprocess

from future import standard_library
standard_library.install_aliases()
from builtins import *
import sys
import syslog

try:
    import simplejson as json
except ImportError:
    import json


CAGEFSCTL = "/usr/sbin/cagefsctl"


def log_error(msg):
    """
    Write message to log
    """
    syslog.syslog("%s: %s" % (__file__, msg))


def main(input_data):
    """
    Run hook action
    """
    data = json.loads(input_data)

    try:
        if data["context"]["event"] == "Accounts::rearrangeacct":
            user = data["data"]["user"]
        else:
            log_error("Unknown event")
            return 2
    except KeyError:
        log_error("Can't get username from event stream")
        return 1

    if subprocess.call("%s --remount %s" % (CAGEFSCTL, user), shell=True, executable='/bin/bash') != 0:
        log_error("Can't remount user %s" % user)
        return 1

    return 0


if "__main__" == __name__:
    sys.exit(main(sys.stdin.read()))
