#!/usr/bin/env python3

import os
import subprocess

#/**
# @file    mountrepo.py
# @brief   Script para montar el repositorio de datos remoto.
#*/

OGIMG = os.getenv('OGIMG', '/opt/opengnsys/images')
ROOTREPO = os.getenv('ROOTREPO', os.getenv('ROOTSERVER'))
ogactiveadmin = os.getenv('ogactiveadmin')
ogprotocol = os.getenv('ogprotocol', 'smb')
ogunit = os.getenv('ogunit', '')
ogstatus = os.getenv('ogstatus')
SERVER = os.getenv('SERVER')
OGCAC = os.getenv('OGCAC')
MSG_MOUNTREPO = "Mounting repository using protocol: {} in mode: {}"

def mount_repo():
    if ogactiveadmin == "true":
        os.environ['boot'] = 'admin'  # ATENCIÓN: siempre en modo "admin".
        subprocess.run(['umount', OGIMG], stderr=subprocess.DEVNULL)

        protocol = ogprotocol
        OGUNIT = f"/{ogunit}" if ogunit else ""
        print(MSG_MOUNTREPO.format(protocol, 'admin'))

        if protocol == 'nfs':
            subprocess.run(['mount.nfs', f'{ROOTREPO}:{OGIMG}{OGUNIT}', OGIMG, '-o', 'rw,nolock'])
        elif protocol == 'smb':
            PASS = get_password()
            subprocess.run(['mount.cifs', f'//{ROOTREPO}/ogimages{OGUNIT}', OGIMG, '-o', f'rw,serverino,acl,username=opengnsys,password={PASS}'])
        elif protocol == 'local':
            handle_local_mount()

def get_password():
    try:
        with open('/scripts/ogfunctions') as f:
            for line in f:
                if 'OPTIONS=' in line:
                    return line.split('pass=')[1].split()[0]
    except Exception:
        pass
    return 'og'

def handle_local_mount():
    if ogstatus == "offline" or not SERVER:
        TYPE = subprocess.getoutput("blkid | grep REPO | awk -F'TYPE=' '{print $2}' | tr -d '\"'")
        if not TYPE:
            if os.path.isdir(f'{OGCAC}/{OGIMG}'):
                subprocess.run(['mount', '--bind', f'{OGCAC}/{OGIMG}', OGIMG])
        else:
            subprocess.run(['mount', '-t', TYPE, 'LABEL=REPO', OGIMG], stderr=subprocess.DEVNULL)
    else:
        if subprocess.run(['smbclient', '-L', SERVER, '-N'], stderr=subprocess.DEVNULL).returncode == 0:
            PASS = get_password()
            subprocess.run(['mount.cifs', f'//{ROOTREPO}/ogimages', OGIMG, '-o', f'rw,serverino,acl,username=opengnsys,password={PASS}'])

if __name__ == "__main__":
    mount_repo()