#!/usr/bin/env python
"""hos-legacymounts cli module: Main module for running the tool as a CLI"""

import logging
import sys

from hos_legacymounts import args
from hos_legacymounts import exceptions
from hos_legacymounts import mounts

__LOG = logging.getLogger()

def main():
    """Entry point for the CLI"""
    # Setup logger
    logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging.INFO)

    # Parse arguments
    parsed_args = args.get_args()
    if parsed_args.timeout:
        try:
            timeout = int(parsed_args.timeout)
        except ValueError:
            __LOG.error("Invalid timeout argument value.")
            sys.exit(1)
    else:
        timeout = 0

    # Define the mounts
    # See: http://rdwiki/HTC_(Application)/Architecture/directory_structure
    # TODO - convert this into a configuration blob
    legacy_mounts = []
    # Define system paths in /usr/local/htc
    legacy_mounts.extend([
        ('/mnt/hos-data/htc', '/usr/local/htc'),
        ('/mnt/hos-data/htc/database', '/usr/local/htc/scripts'),
        ('/mnt/hos-volatile/htc', '/usr/local/htc/readwrite'),
    ])
    # Define /var paths
    legacy_mounts.extend([
        ('/mnt/hos-volatile', '/var/persistent'),
    ])
    # Define legacy paths for remote updates in /htc
    legacy_mounts.extend([
        ('/mnt/hos-data/htc', '/htc'),
        ('/mnt/hos-data/htc/database', '/htc/scripts'),
        ('/mnt/hos-volatile/htc', '/htc/readwrite'),
    ])

    for mount in legacy_mounts:
        source = mount[0]
        target = mount[1]
        __LOG.info("Mounting %s in %s [%ss timeout]...", source, target, timeout)
        try:
            ret = mounts.do_bindmount(source, target, timeout)
        except exceptions.BindMountTimeout as exception:
            __LOG.error(str(exception))
            sys.exit(1)
        if not ret:
            __LOG.error("Failed to mount %s in %s.", source, target)
            sys.exit(1)
        __LOG.info("Mounted %s in %s.", source, target)

    sys.exit(0)

if __name__ == '__main__':
    main()
