#!/usr/bin/python3

#______________________________________
#
# PARAMETROS RECIBIDOS DESDE EL CLIENTE
# $1 modo  (admin, user)
#______________________________________

import os
import sys
import re
import subprocess

import ogGlobals
from SystemLib import ogEcho, ogRaiseError, ogIsRepoLocked
from NetLib import ogGetRepoIp

# Error si llamada no se realliza desde OpenGnsys Client.
prog = sys.argv[0]
if len (sys.argv) != 2:
    print (f'Usage: {prog} <mode>')
    sys.exit (1)

# Salir si el repositorio está bloquedo (tiene ficheros abiertos).
mode = sys.argv[1]
repoip = ogGetRepoIp()
if not repoip:
    ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, 'repo no montado')
    sys.exit (1)
if ogIsRepoLocked():
    ogRaiseError ([], ogGlobals.OG_ERR_LOCKED, f'repo {repoip}')
    sys.exit (1)

# Comprobar protocolo y modo de acceso.
proto = os.getenv ('ogprotocol', 'smb')
if proto not in ['nfs', 'smb']:
    ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'protocolo desconocido {proto}')
    sys.exit (1)
if   'admin' == mode: mount_mode = 'rw'
elif 'user'  == mode: mount_mode = 'ro'
else:
    ogRaiseError ([], ogGlobals.OG_ERR_FORMAT, f'modo desconocido {mode}')
    sys.exit (1)

# Desmontar repositorio y volver a montarlo con el modo adecuado.
subprocess.run (['umount', ogGlobals.OGIMG])
ogEcho ([], 'info', f'Montar repositorio {repoip} por {proto} en modo {mode}')
if 'nfs' == proto:
    subprocess.run (['mount', '-t', 'nfs', f'{repoip}:{ogGlobals.OGIMG}', ogGlobals.OGIMG, '-o', mount_mode])
elif 'smb' == proto:
    pass_option = ''
    with open ('/scripts/ogfunctions', 'r') as fd:
        while True:
            line = fd.readline()
            if not line: break
            if not re.search ('^[\t ]*(export )?OPTIONS=', line): continue
            m = re.search (r'pass=(\w*)', line)
            if m:
                pass_option = m.groups (0)[0]
                break
    if not pass_option: pass_option = 'og'
    subprocess.run (['mount.cifs', f'//{repoip}/ogimages', ogGlobals.OGIMG, '-o', f'{mount_mode},serverino,acl,username=opengnsys,password={pass_option}'])
