import sys
import os

from engine.FileSystemLib import *
from engine.SystemLib import *
from engine.FileLib import *
from engine.NetLib import *

def ogUcastSyntax():
    FUNCNAME = ogUcastSyntax.__name__
    PARM = SESSION = SESSIONPARM = MODE = PORTBASE = PERROR = ADDRESS = TOOL = LEVEL = DEVICE = MBUFFER = SYNTAXSERVER = SYNTAXCLIENT = ""

    # Si se solicita, mostrar ayuda.
    if "help" in sys.argv or len(sys.argv) > 2 and sys.argv[2] == "help":
        ogHelp(f"{FUNCNAME} SENDPARTITION      str_sessionSERVER     str_device str_tools str_level",
               f"{FUNCNAME} RECEIVERPARTITION  str_sessionCLIENT     str_device str_tools str_level",
               f"{FUNCNAME} SENDFILE           str_sessionSERVER     str_file",
               f"{FUNCNAME} RECEIVERFILE       str_sessionCLIENT     str_file",
               "sessionServer syntax:        portbase:ipCLIENT-1:ipCLIENT-2:ipCLIENT-N",
               "sessionServer example:       8000:172.17.36.11:172.17.36.12",
               "sessionClient syntax:        portbase:ipMASTER",
               "sessionClient example:       8000:172.17.36.249")
        return
    PERROR = 0

    # Error si no se reciben $PARM parámetros.
    if "PARTITION" in sys.argv[1]:
        PARM = 5
    else:
        PARM = 3
    if len(sys.argv) != PARM:
        ogRaiseError(OG_ERR_FORMAT, "sin parametros")
        return

    # 1er param check
    if sys.argv[1] not in ["SENDPARTITION", "sendpartition", "RECEIVERPARTITION", "receiverpartition", "SENDFILE", "sendfile", "RECEIVERFILE", "receiverfile"]:
        ogRaiseError(OG_ERR_FORMAT, f"1st param: {sys.argv[1]}")
        PERROR = 1

    # 2º param check
    if "SEND" in sys.argv[1]:
        MODE = "server"
    else:
        MODE = "client"

    ######### No controlamos el numero de elementos de la session unicast porque en el master es variable en numero
    # TODO: diferenciamos los paramatros especificos de la sessión unicast
    # SI: controlamos todos los parametros de la sessión unicast.
    # [ $MODE == "client" ] && SESSIONPARM=2 || SESSIONPARM=6
    OIFS = IFS
    IFS = ':'
    SESSION = sys.argv[2].split(':')
    IFS = OIFS

    # [[ ${#SESSION[*]} == $SESSIONPARM ]]  || ogRaiseError $OG_ERR_FORMAT "parametros session multicast no completa" || PERROR=2# return $?

    # controlamos el PORTBASE de la sesion. Comun.-
    PORTBASE = SESSION[0]
    if PORTBASE not in ["8000", "8001", "8002", "8003", "8004", "8005"]:
        ogRaiseError(OG_ERR_FORMAT, f"McastSession portbase {SESSION[0]}")
        PERROR = 3

    if MODE == "server":
        SIZEARRAY = len(SESSION)
        for i in range(1, SIZEARRAY):
            ADDRESS += f" -O {SESSION[i]}:{PORTBASE}"
            # echo " -O ${SESSION[$i]}:$PORTBASE"
    else:
        ADDRESS = f"{SESSION[1]}:{PORTBASE}"

    # 3er param check - que puede ser un dispositvo o un fichero.
    # [ -n "$(ogGetPath "$3")" ] || ogRaiseError $OG_ERR_NOTFOUND " device or file $3" || PERROR=9 #return $?
    DEVICE = sys.argv[3]

    # 4 y 5 param check .  solo si es sobre particiones.
    if PARM == 5:
        # 4 param check
        if sys.argv[4] not in ["partclone", "PARTCLONE", "partimage", "PARTIMAGE", "ntfsclone", "NTFSCLONE"]:
            ogRaiseError(OG_ERR_NOTFOUND, f" herramienta {sys.argv[4]} no soportada")
            PERROR = 10
        TOOL = sys.argv[4]
        if sys.argv[5] not in ["lzop", "gzip", "LZOP", "GZIP", "0", "1"]:
            ogRaiseError(OG_ERR_NOTFOUND, f" compresor {sys.argv[5]} no valido")
            PERROR = 11

    if PERROR != 0:
        ogRaiseError(OG_ERR_UCASTSYNTAXT, f" {PERROR}")
        return

    # Generamos la instrucción base de unicast -Envio,Recepcion-
    SYNTAXSERVER = f"mbuffer {ADDRESS}"
    SYNTAXCLIENT = f"mbuffer -I {ADDRESS}"

    if sys.argv[1] == "SENDPARTITION":
        PROG1 = ogCreateImageSyntax(DEVICE, " ", TOOL, LEVEL).split("|")[0].split("|")[2].replace(">", "")
        print(f"{PROG1} | {SYNTAXSERVER}")
    elif sys.argv[1] == "RECEIVERPARTITION":
        COMPRESSOR = ogRestoreImageSyntax(" ", DEVICE, TOOL, LEVEL).split("|")[0]
        TOOLS = ogRestoreImageSyntax(" ", DEVICE, TOOL, LEVEL).split("|")[-1]
        print(f"{SYNTAXCLIENT} | {COMPRESSOR} | {TOOLS}")
    elif sys.argv[1] == "SENDFILE":
        print(f"{SYNTAXSERVER} -i {sys.argv[3]}")
    elif sys.argv[1] == "RECEIVERFILE":
        print(f"{SYNTAXCLIENT} -i {sys.argv[3]}")
#
def ogUcastSendPartition():
    FUNCNAME = ogUcastSendPartition.__name__
    # Variables locales
    PART = COMMAND = RETVAL = ""

    # Si se solicita, mostrar ayuda.
    if len(sys.argv) > 1 and sys.argv[1] == "help":
        ogHelp(f"{FUNCNAME} int_ndisk int_npart SessionUNICAST-SERVER tools compresor",
               f"{FUNCNAME} 1 1 8000:172.17.36.11:172.17.36.12 partclone lzop")
        return

    # Error si no se reciben 5 parámetros.
    if len(sys.argv) != 6:
        ogRaiseError(OG_ERR_FORMAT)
        return

    # chequeamos la particion.
    PART = ogDiskToDev(sys.argv[2], sys.argv[3])
    if not PART:
        return

    ogUnmount(sys.argv[2], sys.argv[3])

    # generamos la instrucción a ejecutar.
    COMMAND = ogUcastSyntax("SENDPARTITION", sys.argv[4], PART, sys.argv[5], sys.argv[6])
    RETVAL = 0

    if RETVAL > 0:
        return RETVAL
    else:
        print(COMMAND)
        eval(COMMAND)
        if RETVAL > 0:
            ogRaiseError(OG_ERR_UCASTSENDPARTITION)
            return RETVAL
#
def ogUcastReceiverPartition():
    FUNCNAME = ogUcastReceiverPartition.__name__
    # Variables locales
    PART = COMMAND = RETVAL = ""

    # Si se solicita, mostrar ayuda.
    if len(sys.argv) > 1 and sys.argv[1] == "help":
        ogHelp(f"{FUNCNAME} int_ndisk int_npart SessionMulticastCLIENT tools compresor",
               f"{FUNCNAME} 1 1 8000:ipMASTER partclone lzop")
        return

    # Error si no se reciben 5 parámetros.
    if len(sys.argv) != 6:
        ogRaiseError(OG_ERR_FORMAT)
        return

    # chequeamos la particion.
    PART = ogDiskToDev(sys.argv[2], sys.argv[3])
    if not PART:
        return

    ogUnmount(sys.argv[2], sys.argv[3])

    # generamos la instrucción a ejecutar.
    COMMAND = ogUcastSyntax("RECEIVERPARTITION", sys.argv[4], PART, sys.argv[5], sys.argv[6])
    RETVAL = 0

    if RETVAL > 0:
        return RETVAL
    else:
        print(COMMAND)
        eval(COMMAND)
        if RETVAL > 0:
            ogRaiseError(OG_ERR_UCASTRECEIVERPARTITION)
            return RETVAL
#
def ogUcastSendFile():
    FUNCNAME = ogUcastSendFile.__name__
    # Variables locales
    ARG = ARGS = SOURCE = TARGET = COMMAND = DEVICE = RETVAL = LOGFILE

    # ARGS usado para controlar ubicación de la sesion multicast
    # Si se solicita, mostrar ayuda.
    if len(sys.argv) > 1 and sys.argv[1] == "help":
        ogHelp(f"{FUNCNAME} [str_REPOSITORY] [int_ndisk int_npart] /Relative_path_file sesionMcast(puerto:ip:ip:ip)",
               f"{FUNCNAME}  1 1 /aula1/winxp.img 8000:172.17.36.11:172.17.36.12",
               f"{FUNCNAME}  REPO /aula1/ubuntu.iso sesionUcast",
               f"{FUNCNAME}  CACHE /aula1/winxp.img sesionUcast",
               f"{FUNCNAME}  /opt/opengnsys/images/aula1/hd500.vmx sesionUcast")
        return

    ARGS = sys.argv[1:]
    if ARGS[0].startswith("/"):
        SOURCE = ogGetPath(ARGS[0])
        ARG = 2
        DEVICE = ARGS[0]
    elif ARGS[0].isdigit():
        SOURCE = ogGetPath(ARGS[0], ARGS[1], ARGS[2])
        ARG = 4
        DEVICE = f"{ARGS[0]} {ARGS[1]} {ARGS[2]}"
    else:
        SOURCE = ogGetPath(ARGS[0], ARGS[1])
        ARG = 3
        DEVICE = f"{ARGS[0]} {ARGS[1]}"

    # Error si no se reciben los argumentos ARG necesarios según la opcion.
    if len(sys.argv) != ARG:
        ogRaiseError(OG_ERR_FORMAT)
        return

    # Comprobar fichero origen
    if not ogGetPath(SOURCE):
        ogRaiseError(OG_ERR_NOTFOUND, f" device or file {DEVICE} not found")
        return

    SESSION = sys.argv[ARG]

    # generamos la instrucción a ejecutar.
    COMMAND = ogUcastSyntax("SENDFILE", SESSION, SOURCE)
    RETVAL = 0

    if RETVAL > 0:
        return RETVAL
    else:
        print(COMMAND)
        eval(COMMAND)
        if RETVAL > 0:
            ogRaiseError(OG_ERR_UCASTSENDFILE)
            return RETVAL
#
def ogMcastSyntax():
    FUNCNAME = ogMcastSyntax.__name__
    PERROR = 0

    # Si se solicita, mostrar ayuda.
    if "help" in sys.argv or len(sys.argv) > 2 and sys.argv[2] == "help":
        ogHelp(f"{FUNCNAME} SENDPARTITION      str_sessionSERVER     str_device str_tools str_level",
               f"{FUNCNAME} RECEIVERPARTITION  str_sessionCLIENT     str_device str_tools str_level",
               f"{FUNCNAME} SENDFILE           str_sessionSERVER     str_file",
               f"{FUNCNAME} RECEIVERFILE       str_sessionCLIENT     str_file",
               "sessionServer syntax:        portbase:method:mcastaddress:speed:nclients:ntimeWaitingUntilNclients",
               "sessionServer example:       9000:full-duplex|half-duplex|broadcast:239.194.17.36:80M:50:60",
               "sessionClient syntax:        portbase",
               "sessionClient example:       9000",
               "sessionClient syntax:        portbase:serverIP:TimeOut_session:TimeOut_transmision",
               "sessionClient example:       9000:172.17.88.161:40:120")
        return

    # BEGIN NUMBERS PARAMETERS CHECK AND SESSION OPTIONS IF CLIENT OR SERVER
    if "PARTITION" in sys.argv[1]:
        PARM = 5
    else:
        PARM = 3
    if len(sys.argv) != PARM:
        ogRaiseError(OG_ERR_FORMAT, "sin parametros")
        return

    ogCheckStringInGroup(sys.argv[1], "SENDPARTITION sendpartition RECEIVERPARTITION receiverpartition SENDFILE sendfile RECEIVERFILE receiverfile") or ogRaiseError(OG_ERR_FORMAT, f"1st param: {sys.argv[1]}") or PERROR = 1

    if "SEND" in sys.argv[1]:
        MODE = "server"
    else:
        MODE = "client"

    SESSION = sys.argv[2].split(':')
    if MODE == "client":
        SESSIONPARM = 1
    else:
        SESSIONPARM = 6
    if len(SESSION) != SESSIONPARM:
        ogRaiseError(OG_ERR_FORMAT, "parametros session de cliente multicast no completa") or PERROR = 2

    if MODE == "server":
        ogCheckStringInGroup(SESSION[1], "full-duplex FULL-DUPLEX half-duplex HALF-DUPLEX broadcast BROADCAST") or ogRaiseError(OG_ERR_FORMAT, f"McastSession method {SESSION[1]}") or PERROR = 4
        ogCheckIpAddress(SESSION[2]) or ogRaiseError(OG_ERR_FORMAT, f"McastSession address {SESSION[2]}") or PERROR = 5
        ogCheckStringInReg(SESSION[3], "^[0-9]{1,3}\M$") or ogRaiseError(OG_ERR_FORMAT, f"McastSession bitrate {SESSION[3]}") or PERROR = 6
        ogCheckStringInReg(SESSION[4], "^[0-9]{1,10}$") or ogRaiseError(OG_ERR_FORMAT, f"McastSession nclients {SESSION[4]}") or PERROR = 7
        ogCheckStringInReg(SESSION[5], "^[0-9]{1,10}$") or ogRaiseError(OG_ERR_FORMAT, f"McastSession maxtime {SESSION[5]}") or PERROR = 8

    if PERROR != 0:
        ogRaiseError(OG_ERR_MCASTSYNTAXT, f" {PERROR}")
        return
    # END NUMBERS PARAMETERS CHECK

    # BEGIN SERVER SESSION
    if MODE == "server":
        PORTBASE = SESSION[0]
        METHOD = SESSION[1]
        ADDRESS = SESSION[2]
        BITRATE = SESSION[3]
        NCLIENTS = SESSION[4]
        MAXTIME = SESSION[5]
        CERROR = "8x8/128"
        if "mbuffer" in sys.modules:
            MBUFFER = " --pipe 'mbuffer -q -m 20M' "
        else:
            MBUFFER = ""
        SYNTAXSERVER = f"udp-sender {MBUFFER} --nokbd --portbase {PORTBASE} --{METHOD} --mcast-data-address {ADDRESS} --fec {CERROR} --max-bitrate {BITRATE} --ttl 16 --min-clients {NCLIENTS} --max-wait {MAXTIME} --autostart {MAXTIME} --log /tmp/mcast.log"
    # END SERVER SESSION

    # BEGIN CLIENT SESSION
    if MODE == "client":
        PORTBASE = SESSION[0]
        if ogCheckIpAddress(SESSION[1]):
            SERVERADDRESS = f" --mcast-rdv-address {SESSION[1]}"
        else:
            REPOIP = ogGetRepoIp()
            CLIENTIP = " ".join([addr.split("/")[0] for addr in subprocess.check_output(["ip", "-o", "address", "show", "up"]).decode().splitlines() if "lo" not in addr])
            MASCARA = CLIENTIP.split("/")[1]
            CLIENTIP = CLIENTIP.split("/")[0]
            RIPBT = ""
            IPBT = ""
            for i in range(1, 5):
                RIP = str(int(REPOIP.split(".")[i-1]) + 256)
                RIPB = ""
                while RIP > 0:
                    COCIENTE = RIP // 2
                    RESTO = RIP % 2
                    RIPB = str(RESTO) + RIPB
                    RIP = COCIENTE
                RIPB = RIPB[1:]
                RIPBT += RIPB
                IP = str(int(CLIENTIP.split(".")[i-1]) + 256)
                IPB = ""
                while IP > 0:
                    COCIENTE = IP // 2
                    RESTO = IP % 2
                    IPB = str(RESTO) + IPB
                    IP = COCIENTE
                IPB = IPB[1:]
                IPBT += IPB
            REPOSUBRED = RIPBT[:MASCARA]
            CLIENTSUBRED = IPBT[:MASCARA]
            if REPOSUBRED == CLIENTSUBRED:
                SERVERADDRESS = ""
            else:
                SERVERADDRESS = f" --mcast-rdv-address {REPOIP}"
        if ogCheckStringInReg(SESSION[2], "^[0-9]{1,10}$"):
            if SESSION[2] == "0":
                STARTTIMEOUT = ""
            else:
                STARTTIMEOUT = f" --start-timeout {SESSION[2]}"
        else:
            STARTTIMEOUT = ""
        if ogCheckStringInReg(SESSION[3], "^[0-9]{1,10}$"):
            if SESSION[3] == "0":
                RECEIVERTIMEOUT = ""
            else:
                RECEIVERTIMEOUT = f" --receive-timeout {SESSION[3]}"
        else:
            RECEIVERTIMEOUT = ""
        if "udp-receiver" not in ISUDPCAST:
            STARTTIMEOUT = ""
            RECEIVERTIMEOUT = ""
        SYNTAXCLIENT = f"udp-receiver {MBUFFER} --portbase {PORTBASE}{SERVERADDRESS}{STARTTIMEOUT}{RECEIVERTIMEOUT} --log /tmp/mcast.log"
    # END CLIENT SESSION

    # BEGIN MAIN PROGRAM
    if sys.argv[1] == "SENDPARTITION":
        PROG1 = ogCreateImageSyntax(DEVICE, " ", TOOL, LEVEL).split("|")[0].split("|")[2].replace(">", "")
        print(f"{PROG1} | {SYNTAXSERVER}")
    elif sys.argv[1] == "RECEIVERPARTITION":
        COMPRESSOR = ogRestoreImageSyntax(" ", DEVICE, TOOL, LEVEL).split("|")[0]
        TOOLS = ogRestoreImageSyntax(" ", DEVICE, TOOL, LEVEL).split("|")[-1]
        print(f"{SYNTAXCLIENT} | {COMPRESSOR} | {TOOLS}")
    elif sys.argv[1] == "SENDFILE":
        print(f"{SYNTAXSERVER} --file {sys.argv[3]}")
    elif sys.argv[1] == "RECEIVERFILE":
        print(f"{SYNTAXCLIENT} --file {sys.argv[3]}")
    # END MAIN PROGRAM
#
def ogMcastSendFile():
    FUNCNAME = ogMcastSendFile.__name__
    # Variables locales
    ARGS = ARG = SOURCE = TARGET = COMMAND = DEVICE = RETVAL = LOGFILE

    # LOGFILE = "/tmp/mcast.log"

    # ARGS usado para controlar ubicación de la sesion multicast
    # Si se solicita, mostrar ayuda.
    if len(sys.argv) > 1 and sys.argv[1] == "help":
        ogHelp(f"{FUNCNAME} [str_REPOSITORY] [int_ndisk int_npart] /Relative_path_file sesionMcast",
               f"{FUNCNAME}  1 1 /aula1/winxp.img sesionMcast",
               f"{FUNCNAME}  REPO /aula1/ubuntu.iso sesionMcast",
               f"{FUNCNAME}  CACHE /aula1/winxp.img sesionMcast",
               f"{FUNCNAME}  /opt/opengnsys/images/aula1/hd500.vmx sesionMcast")
        return

    ARGS = sys.argv[1:]
    if ARGS[0].startswith("/"):
        SOURCE = ogGetPath(ARGS[0])
        ARG = 2
        DEVICE = ARGS[0]
    elif ARGS[0].isdigit():
        SOURCE = ogGetPath(ARGS[0], ARGS[1], ARGS[2])
        ARG = 4
        DEVICE = f"{ARGS[0]} {ARGS[1]} {ARGS[2]}"
    else:
        SOURCE = ogGetPath(ARGS[0], ARGS[1])
        ARG = 3
        DEVICE = f"{ARGS[0]} {ARGS[1]}"

    # Error si no se reciben los argumentos ARG necesarios según la opcion.
    if len(sys.argv) != ARG:
        ogRaiseError(OG_ERR_FORMAT)
        return

    # Comprobar fichero origen
    if not ogGetPath(SOURCE):
        ogRaiseError(OG_ERR_NOTFOUND, f" device or file {DEVICE} not found")
        return

    SESSION = sys.argv[ARG]

    # generamos la instrucción a ejecutar.
    COMMAND = ogMcastSyntax("SENDFILE", SESSION, SOURCE)
    RETVAL = 0

    if RETVAL > 0:
        return RETVAL
    else:
        print(COMMAND)
        eval(COMMAND)
        if RETVAL > 0:
            ogRaiseError(OG_ERR_MCASTSENDFILE)
            return RETVAL
#
def ogMcastReceiverFile():
    # Variables locales
    FUNCNAME = ogMcastReceiverFile.__name__
    ARGS = ARG = TARGETDIR = TARGETFILE = COMMAND = ""

    # Si se solicita, mostrar ayuda.
    if len(sys.argv) > 1 and sys.argv[1] == "help":
        ogHelp(f"{FUNCNAME} [str_portMcast] [[Relative_path_file] | [str_REPOSITORY path_file] | [int_ndisk int_npart path_file]]",
               f"{FUNCNAME} 9000 /PS1_PH1.img",
               f"{FUNCNAME} 9000 CACHE /aula1/PS2_PH4.img",
               f"{FUNCNAME} 9000 1 1 /isos/linux.iso")
        return

    ARGS = sys.argv[1:]
    if ARGS[1].startswith("/"):
        TARGETDIR = ogGetParentPath(ARGS[1])
        ARG = 2
    elif ARGS[1].isdigit():
        TARGETDIR = ogGetParentPath(ARGS[1], ARGS[2], ARGS[3])
        ARG = 4
    else:
        TARGETDIR = ogGetParentPath(ARGS[1], ARGS[2])
        ARG = 3

    # Error si no se reciben los argumentos ARG necesarios según la opcion.
    if len(sys.argv) != ARG:
        ogRaiseError(OG_ERR_FORMAT, "Parametros no admitidos")
        return

    # obtenemos el nombre del fichero a descargar.
    TARGETFILE = os.path.basename(ARGS[ARG])

    # generamos la instrucción a ejecutar.
    COMMAND = ogMcastSyntax("RECEIVERFILE", sys.argv[1], f"{TARGETDIR}/{TARGETFILE}")
    RETVAL = 0

    if RETVAL > 0:
        return RETVAL
    else:
        print(COMMAND)
        eval(COMMAND)
        if RETVAL > 0:
            ogRaiseError(OG_ERR_MCASTRECEIVERFILE, TARGETFILE)
            return RETVAL
        #[ -s "$LOGFILE" ] || return 21
#
def ogMcastSendPartition():
    FUNCNAME = ogMcastSendPartition.__name__
    # Variables locales
    PART = ""
    COMMAND = ""
    RETVAL = 0

    # Si se solicita, mostrar ayuda.
    if len(sys.argv) > 1 and sys.argv[1] == "help":
        ogHelp(f"{FUNCNAME} int_ndisk int_npart SessionMulticastSERVER tools compresor",
               f"{FUNCNAME} 1 1 9000:full-duplex:239.194.37.31:50M:20:2 partclone lzop")
        return

    # Error si no se reciben 5 parámetros.
    if len(sys.argv) != 6:
        ogRaiseError(OG_ERR_FORMAT)
        return

    # chequeamos la particion.
    PART = ogDiskToDev(sys.argv[2], sys.argv[3])
    if not PART:
        return

    ogUnmount(sys.argv[2], sys.argv[3])

    # generamos la instrucción a ejecutar.
    COMMAND = ogMcastSyntax("SENDPARTITION", sys.argv[4], PART, sys.argv[5], sys.argv[6])
    RETVAL = 0

    if RETVAL > 0:
        return RETVAL
    else:
        print(COMMAND)
        eval(COMMAND)
        if RETVAL > 0:
            ogRaiseError(OG_ERR_MCASTSENDPARTITION)
            return RETVAL
#
def ogMcastReceiverPartition():
    FUNCNAME = ogMcastReceiverPartition.__name__
    # Variables locales
    PART = ""
    COMMAND = ""
    RETVAL = 0

    # Si se solicita, mostrar ayuda.
    if len(sys.argv) > 1 and sys.argv[1] == "help":
        ogHelp(f"{FUNCNAME} int_ndisk int_npart SessionMulticastCLIENT tools compresor",
               f"{FUNCNAME} 1 1 9000 partclone lzop")
        return

    # Error si no se reciben 5 parámetros.
    if len(sys.argv) != 6:
        ogRaiseError(OG_ERR_FORMAT)
        return

    # chequeamos la particion.
    PART = ogDiskToDev(sys.argv[2], sys.argv[3])
    if not PART:
        return

    ogUnmount(sys.argv[2], sys.argv[3])

    # generamos la instrucción a ejecutar.
    COMMAND = ogMcastSyntax("RECEIVERPARTITION", sys.argv[4], PART, sys.argv[5], sys.argv[6])
    RETVAL = 0

    if RETVAL > 0:
        return RETVAL
    else:
        print(COMMAND)
        eval(COMMAND)
        if RETVAL > 0:
            ogRaiseError(OG_ERR_MCASTSENDPARTITION)
            return RETVAL
#
def ogMcastRequest():
    # Variables locales
    FILE = ""
    PROTOOPT = ""
    PORT = ""
    PORTAUX = ""
    REPOIP = ""
    REPOPORTAUX = ""
    REPEAT = 0
    OGUNIT = "$(df|awk '/ogimages/ {print $1}'|cut -d/ -f5)/"

    # Si se solicita, mostrar ayuda.
    if len(sys.argv) > 1 and sys.argv[1] == "help":
        ogHelp(f"{FUNCNAME} path_filename str_mcastoptions")
        return

    # Error si no se reciben 2 parámetros.
    if len(sys.argv) != 3:
        ogRaiseError(OG_ERR_FORMAT)
        return

    FILE = f"{OGUNIT}{sys.argv[1]}"
    PROTOOPT = sys.argv[2]

    # TODO: CONTROL PARAMETROS

    PORT = PROTOOPT.split(":")[0]
    PORTAUX = str(int(PORT) + 1)
    REPOIP = ogGetRepoIp()
    REPOPORTAUX = 2009
    REPEAT = 0
    while not nmap -n -sU -p $PORTAUX $REPOIP | grep open:
        REPEAT += 1
        if REPEAT >= 6:
            ogRaiseError("session log", OG_ERR_PROTOCOLJOINMASTER, f"MULTICAST {FILE} {PROTOOPT} {FILELIST}")
            return
        print(f"{MSG_SCRIPTS_TASK_START}: hose {REPOIP} {REPOPORTAUX} --out sh -c 'echo -ne START_MULTICAST {FILE} {PROTOOPT}'")
        # update-cache:
        hose(REPOIP, REPOPORTAUX, "--out sh -c 'echo -ne START_MULTICAST {FILE} {PROTOOPT}'")
        # multicas-direct: hose {REPOIP} 2009 --out sh -c 'echo -ne START_MULTICAST /{IMAGE}.img {OPTPROTOCOLO}'
        time.sleep(10)
#
