#!/usr/bin/python3
import logging
import os
import sys

#
# HbkCD - Handbrake Control Daemon
#

###############################################################################
# Configuration Options
###############################################################################
LOGFILE_PATH = '/var/log/hbkcd/hbkcd.log'
LOG_FORMAT_STR = '%(asctime)s|%(levelname)s|%(filename)s:%(lineno)s|%(message)s'
LOG_DATE_FORMAT_STR = '%a %b %d %H:%M:%S %Y'
DEFAULT_LOG_LEVEL = logging.DEBUG

# Absolute path the to the HandbrakeCLI executable
HANDBRAKE_PATH = '/opt/local/bin/HandBrakeCLI'

# Path to queue file. Note that there is nothing special about this file, it
# is simply a text file containing a list of paths to video files to re-enocde
QUEUE_FILE_PATH = '/home/dsorber/encode_queue'

def check_configuration():
    """ Check runtime parameters for correctness before attempting to use them.
    """
    
    # Make sure specified HandbrakeCLI path exists and is a file
    if not os.path.isfile(HANDBRAKE_PATH):
        logging.error('Handbrake does not exist at path: {:s}'
                      .format(HANDBRAKE_PATH))
        return False
    
    # Make sure the specified HandbrakeCLI file is executable
    if not os.access(HANDBRAKE_PATH, os.X_OK):
        logging.error('Handbrake exists but is not executable ({:s})'
                      .format(HANDBRAKE_PATH))
        return False
        
    # Make sure specified encode queue file exists and is a file
    if not os.path.isfile(QUEUE_FILE_PATH):
        logging.error('The specified encode queue file ({:s}) does not exist, '
                      'please create it to proceed'.format(QUEUE_FILE_PATH))
        return False
    
    logging.debug('Runtime configuration checks OKAY')
    
    return True
    

def main():

    # Configure logging before attempting anything serious
    logging.basicConfig(format=LOG_FORMAT_STR, 
                        datefmt=LOG_DATE_FORMAT_STR, 
                        # ~ filename=LOGFILE_PATH, 
                        level=DEFAULT_LOG_LEVEL)
    
    # ~ print('foobar', file=sys.stderr)
    logging.info('hbkcf started')
    
    # Validate runtime configuration before proceeding
    if not check_configuration():
        return -1
    
    return 0
    
if __name__ == '__main__':
    sys.exit(main())
