#!/opt/cloudlinux/venv/bin/python3
# Copyright 1999-2026. WebPros International GmbH. All rights reserved.
# vim:ft=python:

import argparse
import logging
import os.path
import sys

PASSENGER_LIBDIR='/usr/share/passenger'
PASSENGER_TMP='/run/passenger'
PASSENGER_RBENV='/var/lib/rbenv'
README_PATH='/usr/share/doc/passenger-cagefs-6.1.2/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/cagefs/cagefs.mp', PASSENGER_TMP)
            clcagefs.setup_mount_dir_cagefs(PASSENGER_TMP,
                added_by='passenger-cagefs',
            )

            logging.info('adding %s to /etc/cagefs/cagefs.mp', PASSENGER_LIBDIR)
            clcagefs.setup_mount_dir_cagefs(PASSENGER_LIBDIR,
                added_by='passenger-cagefs',
                prefix='!',  # readonly
            )

            if os.path.isdir(PASSENGER_RBENV):
                logging.info('adding %s to /etc/cagefs/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,
                )

                logger.warning('CageFS mount points for Phusion Passenger were configured. '
                               'You may need to manually call the following commands '
                               'to complete passenger-cagefs configuration:')
                logger.warning('  cagefsctl --force-update')
                logger.warning('  cagefsctl --remount-all')
                logger.warning('  systemctl reload nginx.service httpd.service')
        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()
