#!/opt/alt/python27/bin/python
# Copyright 2019. Plesk International GmbH. All rights reserved.
# vim:ft=python:

import argparse
import logging
import os.path
import sys

PASSENGER_TMP='/run/passenger'
PASSENGER_RBENV='/var/lib/rbenv'
README_PATH='/usr/share/doc/passenger-cagefs-5.3.5.1/README'
instruction = 'See {0} for details and instructions how to complete configuration.'.format(README_PATH)


def main():
    arg_parser = argparse.ArgumentParser(
        description='Add CageFS mount points necessary for Phusion Passenger',
        epilog=instruction,
    )
    arg_parser.add_argument('-d', '--debug', '-v', '--verbose',
        dest='verbose',
        action='store_true',
        help='verbose mode',
    )
    args = arg_parser.parse_args()

    logging.basicConfig(format='%(filename)s: %(levelname)6s: %(message)s')
    logger = logging.getLogger('')
    if args.verbose:
        logger.setLevel(logging.INFO)

    try:
        from clcommon import clcagefs
    except ImportError:
        logger.error('clcommon.cagefs python module is unavailable')
        logger.error('%s', instruction)
        sys.exit(1)

    try:
        if clcagefs.is_cagefs_present():
            # on CloudLinux-6 clcagefs.setup_mount_dir_cagefs() has no remount_cagefs argument
            logging.info('adding %s to /etc/cagfs/cagefs.mp', PASSENGER_TMP)
            clcagefs.setup_mount_dir_cagefs(PASSENGER_TMP,
                added_by='passenger-cagefs',
            )

            if os.path.isdir(PASSENGER_RBENV):
                logging.info('adding %s to /etc/cagfs/cagefs.mp', PASSENGER_RBENV)
                clcagefs.setup_mount_dir_cagefs(PASSENGER_RBENV,
                    added_by='passenger-cagefs',
                    prefix='!',  # readonly
                )

            else:
                logger.info('%s is not added to /etc/cagefs/cagefs.mp, it does not exist',
                    PASSENGER_RBENV,
                )
        else:
            logger.info('nothing to do - CageFS is not installed')

    except Exception as e:
        logger.error('unable to setup passenger-cagefs: %s', str(e))
        logger.error('%s', instruction)
        sys.exit(1)


if __name__ == '__main__':
    main()
