#!/usr/bin/env python3
import os
import sys
import subprocess
import NetLib
import SystemLib

def main():
    if len(sys.argv) != 2:
        print("Usage: CambiarAcceso.py <mode>")
        sys.exit(1)

    mode = sys.argv[1]
    repo_ip = NetLib.ogGetRepoIp()

    if not repo_ip:
        SystemLib.ogRaiseError("OG_ERR_NOTFOUND", "repo no montado")

    if SystemLib.ogIsRepoLocked():
        SystemLib.ogRaiseError("OG_ERR_LOCKED", f"repo {repo_ip}")

    proto = os.getenv("ogprotocol", "smb")
    if proto not in ["nfs", "smb"]:
        SystemLib.ogRaiseError("OG_ERR_FORMAT", f"protocolo desconocido {proto}")

    if mode == "admin":
        mount_mode = "rw"
    elif mode == "user":
        mount_mode = "ro"
    else:
        SystemLib.ogRaiseError("OG_ERR_FORMAT", f"modo desconocido {mode}")

    OGIMG = os.getenv("OGIMG", "/mnt/OGIMG")
    OGUNIT = os.getenv("OGUNIT", "")
    if OGUNIT:
        OGUNIT = f"/{OGUNIT}"

    subprocess.run(["umount", OGIMG], check=True)
    SystemLib.ogEcho("info", f"Montar repositorio {repo_ip} por {proto} en modo {mode}")

    if proto == "nfs":
        subprocess.run(["mount", "-t", "nfs", f"{repo_ip}:{OGIMG}{OGUNIT}", OGIMG, "-o", mount_mode], check=True)
    elif proto == "smb":
        with open("/scripts/ogfunctions", "r") as f:
            for line in f:
                if "OPTIONS=" in line:
                    pass_option = line.split("pass=")[1].split()[0]
                    break
            else:
                pass_option = "og"
        subprocess.run(["mount.cifs", f"//{repo_ip}/ogimages{OGUNIT}", OGIMG, "-o", f"{mount_mode},serverino,acl,username=opengnsys,password={pass_option}"], check=True)

if __name__ == "__main__":
    main()
