#!/usr/bin/python3

import os
import sys
import shutil

import ogGlobals
import SystemLib
import CacheLib

#/**
#         updateBootCache
#@brief   acelerador arranque pxe. incorpora a la cache el initrd y el kernel.
#@param 1 
#@param ejemplo:  
#@return  
#@exception OG_ERR_NOTCACHE   # 15 si cache no existe 15
#@exception OG_ERR_NOTFOUND=2        # Fichero o dispositivo no encontrado.
#@note   
#@todo: 
#*/ ##

oglivedir = os.environ.get ('oglivedir', 'ogLive')
ogbtftp = f'/opt/oglive/tftpboot/{oglivedir}'
ogbcache = f'{ogGlobals.OGCAC}/boot/{oglivedir}'

#control de errores
if not os.path.isdir (ogbtftp):
    SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTFOUND, ogbtftp)
    os.exit (1)

if not CacheLib.ogMountCache():
    SystemLib.ogRaiseError ([], ogGlobals.OG_ERR_NOTCACHE, 'CACHE')
    os.exit (1)

os.makedirs (ogbcache, exist_ok=True)
	
servervmlinuz = serverinitrd = cachevmlinuz = cacheinitrd = ''
	# comparamos los del server
if os.path.exists (f'{ogbtftp}/ogvmlinuz.sum'):
    with open     (f'{ogbtftp}/ogvmlinuz.sum',     'r') as fd: servervmlinuz = fd.read().strip()
if os.path.exists (f'{ogbtftp}/oginitrd.img.sum'):
    with open     (f'{ogbtftp}/oginitrd.img.sum',  'r') as fd: serverinitrd  = fd.read().strip()
	
	#comparamos los de la cache
if os.path.exists (f'{ogbcache}/ogvmlinuz.sum'):
    with open     (f'{ogbcache}/ogvmlinuz.sum',    'r') as fd: cachevmlinuz  = fd.read().strip()
if os.path.exists (f'{ogbcache}/oginitrd.img.sum'):
    with open     (f'{ogbcache}/oginitrd.img.sum', 'r') as fd: cacheinitrd   = fd.read().strip()

print (f'MD5 on SERVER: {servervmlinuz} {serverinitrd}')
print (f'MD5 on  CACHE: {cachevmlinuz} {cacheinitrd}')

do_reboot = ''
if cachevmlinuz != servervmlinuz:
    print ('ogvmlinuz updating')
    shutil.copy2 (f'{ogbtftp}/ogvmlinuz',     f'{ogbcache}/ogvmlinuz')
    shutil.copy2 (f'{ogbtftp}/ogvmlinuz.sum', f'{ogbcache}/ogvmlinuz.sum')
    do_reboot = 'true'

if cacheinitrd != serverinitrd:
    print ('oginitrd updating')
    shutil.copy2 (f'{ogbtftp}/oginitrd.img',     f'{ogbcache}/oginitrd.img')
    shutil.copy2 (f'{ogbtftp}/oginitrd.img.sum', f'{ogbcache}/oginitrd.img.sum')
    do_reboot = 'true'

print (do_reboot)
sys.exit (0)
