import subprocess
import sys
import os

from engine.FileLib import *
from engine.SystemLib import *

def ogChangeRepo():
    SRCIMG = ""
    NEWREPO = ""
    REPO = ""
    OGUNIT = ""

    if len(sys.argv) < 2:
        print("Usage: ogChangeRepo IPREPO [ OgUnit ]")
        print("Example: ogChangeRepo 10.1.120.3")
        print("Example: ogChangeRepo 10.1.120.3 cdc")
        return

    if sys.argv[1] == "help":
        print("Usage: ogChangeRepo IPREPO [ OgUnit ]")
        print("Example: ogChangeRepo 10.1.120.3")
        print("Example: ogChangeRepo 10.1.120.3 cdc")
        return

    if len(sys.argv) >= 2:
        NEWREPO = sys.argv[1]

    # Opciones de montaje: lectura o escritura
    subprocess.run(["mount", "|", "grep", "ogimages.*rw,"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    RW = ",rw" if subprocess.returncode == 0 else ",ro"

    # Si REPO tomamos el repositorio y la unidad organizativa actual
    REPO = ogGetRepoIp()
    OGUNIT = subprocess.run(["df", "|", "awk", "-F", " ", "'/ogimages/ {sub(\"//.*/ogimages\",\"\",$1); sub(\"/\",\"\",$1);  print $1}'"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().strip()

    # Parametros de entrada. Si $1 = "REPO" dejo el repositorio actual
    if sys.argv[1].upper() == "REPO":
        NEWREPO = REPO

    # Si $1 y $2 son el repositorio y la OU actual me salgo
    if NEWREPO == REPO and sys.argv[2] == OGUNIT:
        return 0

    subprocess.run(["source", "/scripts/functions"], shell=True)
    subprocess.run(["source", "/scripts/ogfunctions"], shell=True)
    subprocess.run(["umount", OGIMG])

    if sys.argv[2] == "":
        SRCIMG = "ogimages"
    else:
        SRCIMG = "ogimages/" + sys.argv[2]

    subprocess.run(["eval", "$(grep \"OPTIONS=\" /scripts/ogfunctions)"])

    ogEcho("session", "log", MSG_HELP_ogChangeRepo + " " + NEWREPO + " " + sys.argv[2].rstrip())
    ogConnect(NEWREPO, ogprotocol, SRCIMG, OGIMG, RW)

    # Si da error volvemos a montar el inicial
    if subprocess.returncode != 0:
        ogConnect(REPO, ogprotocol, SRCIMG, OGIMG, RW)
        ogRaiseError("session", OG_ERR_REPO, NEWREPO)
        return subprocess.returncode
    
def ogGetGroupDir():
    REPO = ""
    DIR = ""
    GROUP = ""

    if len(sys.argv) < 2:
        ogHelp("ogGetGroupDir", "ogGetGroupDir str_repo", "ogGetGroupDir REPO  ==>  /opt/opengnsys/images/groups/Grupo1")
        return

    if len(sys.argv) == 1:
        REPO = "REPO"
    else:
        REPO = sys.argv[1]

    GROUP = ogGetGroupName()
    if GROUP:
        DIR = ogGetPath(REPO, "/groups/" + GROUP, stderr=subprocess.DEVNULL)
        if os.path.isdir(DIR):
            print(DIR)

    return 0

def ogGetGroupName():
    if len(sys.argv) >= 2 and sys.argv[1] == "help":
        ogHelp("ogGetGroupName", "ogGetGroupName", "ogGetGroupName  =>  Grupo1")
        return

    if "group" in globals() and group:
        print(group)

    return 0

def ogGetHostname():
    HOST = ""

    if len(sys.argv) >= 2 and sys.argv[1] == "help":
        ogHelp("ogGetHostname", "ogGetHostname", "ogGetHostname  =>  pc1")
        return

    # Tomar nombre de la variable HOSTNAME
    HOST = os.getenv("HOSTNAME")

    # Si no, tomar del DHCP, opción host-name
    if not HOST:
        with open("/var/lib/dhcp3/dhclient.leases", "r") as f:
            for line in f:
                if "option host-name" in line:
                    HOST = line.split('"')[1]
                    break

    # Si no, leer el parámetro del kernel hostname
    if not HOST:
        with open("/proc/cmdline", "r") as f:
            cmdline = f.read()
            HOST = re.search(r"hostname=([^ ]+)", cmdline)
            if HOST:
                HOST = HOST.group(1)

    if HOSTNAME != HOST:
        os.environ["HOSTNAME"] = HOST

    if HOST:
        print(HOST)

def ogGetIpAddress():
    IP = ""

    if len(sys.argv) >= 2 and sys.argv[1] == "help":
        ogHelp("ogGetIpAddress", "ogGetIpAddress", "ogGetIpAddress  =>  192.168.0.10")
        return

    if "IPV4ADDR" in os.environ:
        IP = os.environ["IPV4ADDR"]
    else:
        # Obtener direcciones IP.
        if "DEVICE" in os.environ:
            IP = subprocess.run(["ip", "-o", "address", "show", "up", "dev", os.environ["DEVICE"]], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split()
        else:
            IP = subprocess.run(["ip", "-o", "address", "show", "up"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split()

        IP = [addr.split("/")[0] for addr in IP if "inet" in addr]

    # Mostrar solo la primera.
    if IP:
        print(IP[0])

    return 0

def ogGetMacAddress():
    MAC = ""

    if len(sys.argv) >= 2 and sys.argv[1] == "help":
        ogHelp("ogGetMacAddress", "ogGetMacAddress", "ogGetMacAddress  =>  00:11:22:33:44:55")
        return

    # Obtener direcciones Ethernet.
    if "DEVICE" in os.environ:
        MAC = subprocess.run(["ip", "-o", "link", "show", "up", "dev", os.environ["DEVICE"]], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split()
        MAC = [addr.upper() for addr in MAC if "ether" in addr]
    else:
        MAC = subprocess.run(["ip", "-o", "link", "show", "up"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split()
        MAC = [addr.upper() for addr in MAC if "ether" in addr and "lo" not in addr]

    # Mostrar solo la primera.
    if MAC:
        print(MAC[0])

    return 0

def ogGetNetInterface():
    if len(sys.argv) >= 2 and sys.argv[1] == "help":
        ogHelp("ogGetNetInterface", "ogGetNetInterface", "ogGetNetInterface  =>  eth0")
        return

    if "DEVICE" in os.environ:
        print(os.environ["DEVICE"])

    return 0

def ogGetRepoIp():
    # Variables locales.
    SOURCE = ""
    FSTYPE = ""

    # Mostrar ayuda.
    if len(sys.argv) >= 2 and sys.argv[1] == "help":
        ogHelp("ogGetRepoIp", "ogGetRepoIp", "ogGetRepoIp  =>  192.168.0.2")
        return

    # Obtener direcciones IP, según el tipo de montaje.
    output = subprocess.run(["findmnt", "-P", "-o", "SOURCE,FSTYPE", OGIMG], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().strip()
    lines = output.split("\n")
    for line in lines:
        fields = line.split()
        if len(fields) == 2:
            if fields[1] == "nfs":
                SOURCE = fields[0].split(":")[0]
            elif fields[1] == "cifs":
                SOURCE = fields[0].split("/")[2]

    if SOURCE:
        print(SOURCE)

    return 0

def ogGetServerIp():
    # Variables locales.
    SOURCE = ""
    FSTYPE = ""

    # Mostrar ayuda.
    if len(sys.argv) >= 2 and sys.argv[1] == "help":
        ogHelp("ogGetServerIp", "ogGetServerIp", "ogGetServerIp  =>  192.168.0.2")
        return

    # Obtener direcciones IP, según el tipo de montaje.
    output = subprocess.run(["findmnt", "-P", "-o", "SOURCE,FSTYPE", OGIMG], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().strip()
    lines = output.split("\n")
    for line in lines:
        fields = line.split()
        if len(fields) == 2:
            if fields[1] == "nfs":
                SOURCE = fields[0].split(":")[0]
            elif fields[1] == "cifs":
                SOURCE = fields[0].split("/")[2]

    if SOURCE:
        print(SOURCE)

    return 0

def ogMakeGroupDir():
    REPO = ""
    DIR = ""
    GROUP = ""

    if len(sys.argv) < 2:
        ogHelp("ogMakeGroupDir", "ogMakeGroupDir str_repo", "ogMakeGroupDir", "ogMakeGroupDir REPO")
        return

    if len(sys.argv) == 1:
        REPO = "REPO"
    else:
        REPO = sys.argv[1]

    DIR = ogGetPath(REPO, "/groups/" + ogGetGroupName(), stderr=subprocess.DEVNULL)
    if DIR:
        subprocess.run(["mkdir", "-p", DIR], stderr=subprocess.DEVNULL)

    return 0