#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
import signal
import socket
from utils.directoryUtil import DirectoryUtil
from common.appConfig import GetLogger

def get_ip_address():
    """Get the IP address of the current machine."""
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # This doesn't have to be reachable, just an address on the same network
        s.connect(('10.254.254.254', 1))
        ip_address = s.getsockname()[0]
    except Exception:
        ip_address = '127.0.0.1'
    finally:
        s.close()
    return ip_address

def customSignalHandler(signal, frame):
    ip_address = get_ip_address()
    msg1=f'Custom signal handler: Cleanup operations can be done here.'
    msg2=f'The IP address of this machine is: {ip_address}'
    print(msg1)
    logger = GetLogger()
    logger.warning(msg1)
    logger.warning(msg2)
    
    sys.exit(0)

def main():
    logDirectory="log"
    if not DirectoryUtil.check_directory_exists(logDirectory):
        DirectoryUtil.create_directory(logDirectory)
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wtoaamapi.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    
    # Register custom signal handlers
    signal.signal(signal.SIGINT, customSignalHandler)  # Handle Ctrl-C
    signal.signal(signal.SIGTERM, customSignalHandler)  # Handle kill command

    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
