<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import configparser
import importlib
import json
import logging
import os
import random
import socket
import sys

logger = logging.getLogger(__name__)


"""
Get Linpeas result
"""


def get_gtfobins():
    data = {}

    try:
        with open(
            f"{os.getcwd()}/gtfobins.json",
            "r",
        ) as f:
            data = json.load(f)
    except IOError:
        pass

    return data


"""
Get Linpeas result
"""


def get_linpeas_result(target):
    data = {}

    try:
        with open(
            f"{os.getcwd()}/targets/{target}/results/linpeas_result.json",
            "r",
        ) as f:
            data = json.load(f)
    except IOError:
        pass

    return data


"""
Function to load result from a specific module
"""


def load_result(target, module):
    target_loc = f"{os.getcwd()}/targets/{target}/results"

    try:
        data = {}
        with open(f"{target_loc}/{module.lower()}_result.json", "r") as f:
            data = json.load(f)

        return data
    except IOError:
        return {}


"""
Function for getting config file
"""


def tool_config():
    config = configparser.ConfigParser()
    config.read(os.path.join(os.getcwd(), "config.ini"))
    return config


"""
Function to get class from module file
"""


def get_module(module):
    _module_class = f"{module.capitalize()}Module"

    try:
        return getattr(
            importlib.import_module(f"modules.{module.lower()}"), _module_class
        )
    except Exception:
        return None


"""
Function to get config for module
"""


def get_module_config(config, module):
    if config.has_section(module.capitalize()):
        return config[module.capitalize()]
    else:
        return []


"""
Function for getting all modules with a certain type
Supports three types: IG, VA, EX

And also, target type
Supports two target types: INTERNAL, EXTERNAL
"""


def get_module_types(type, target_type):
    modules = os.listdir(os.path.join(f"{os.getcwd()}/modules"))

    # Get .py modules
    modules = [m for m in modules if m.endswith(".py")]
    modules = [m.split(".")[0] for m in modules]

    modules_type = []

    for module in modules:
        cls = get_module(module)
        if type in cls._type and cls._target_type == target_type:
            modules_type.append(module)

    return modules_type


"""
Function for creating new target in /targets directory
"""


def create_new_target(target):
    target_loc = f"{os.getcwd()}/targets/{target}"

    # Create directories
    os.mkdir(os.path.join(f"{os.getcwd()}/targets", target))
    os.mkdir(os.path.join(target_loc, "regtests"))
    os.mkdir(os.path.join(target_loc, "results"))

    # Create config file
    with open(f"{target_loc}/config.ini", "w+") as f:
        config = configparser.ConfigParser()
        config.add_section("General")
        config.set("General", "target", target)
        config.set("General", "regression", "True")

        # Add all module configurations
        modules = os.listdir(os.path.join(f"{os.getcwd()}/modules"))

        # Get .py modules
        modules = [m for m in modules if m.split(".")[-1] == "py"]
        modules = [m.split(".")[0] for m in modules]

        # All modules to config file, together with default configs
        for module in modules:
            config.add_section(module.capitalize())
            cls = get_module(module)

            if cls:
                config.set(module.capitalize(), "enabled", str(False))
                if cls._defaults:
                    for key, value in cls._defaults.items():
                        config.set(module.capitalize(), str(key), str(value))

        config.write(f)

    # Create topology, with
    with open(f"{target_loc}/topology.json", "w+") as f:
        json.dump(
            {
                "tool": {
                    "user": "kali",
                    "password": "<PASSWORD>",
                    "parent": None,
                    "host": socket.gethostbyname(socket.gethostname()),
                },
                "inter": {
                    "user": "kali",
                    "password": "<PASSWORD>",
                    "parent": "tool",
                    "host": "10.10.10.10"
                },
                "target": {
                    "user": "kali",
                    "password": "<PASSWORD>",
                    "parent": "inter",
                    "host": target,
                },
            },
            f,
            indent=4,
        )


"""
Generate random number
"""


def generate_random(total):
    number = ""
    for _ in range(total):
        number += str(random.randint(0, 9))

    return number


def remove_suffix(input_string, suffix):
    if suffix and input_string.endswith(suffix):
        return input_string[: -len(suffix)]
    return input_string


"""
Information about internal system
"""


def python_version():
    return int(sys.version_info[0])


def os_name():
    return sys.platform


def logger_class(cls, msg, type):
    m_message = f"[{cls.__class__.__name__}] {msg}"

    if type == "info":
        logger.info(m_message)
    elif type == "error":
        logger.error(m_message)
    elif type == "debug":
        logger.debug(m_message)
    elif type == "warn":
        logger.warn(m_message)
