__author__= 'Doble Engineering'

import glob
import subprocess
import logging
import logfiles

"""
MSOHFD-987

23Jun2016
These are the changes done to create the paritions as part of the upgrade of the firmware
I will try to document what all trivial things are done here probably this will/should going to the wiki


Typical installation process is a zip file is given to the DTA.
DTA transfers the zip file using the messages(21h and 22h)
tos run M7_fwupdate.sh <downloaded zip file>
M7_fwupdate.sh is from the firmware which is already running on the M7
example 1.2.6.6 M7_fwupdate.sh will be consuming the 1.2.7.12 zip file for the upgrade
M7_fwupdate.sh will be shipping the zip file to the other hosts
and run the M7_sysUpdater.py(this file) will be called to proceed with the installation

For creating the partitions, for which the packages are required to be installed before running
the actual updater which used to be M7_sysUpdater.py(this file)

This is a puzzle, where before running M7_sysUpdater.py, some libraries need to be installed but
the file fwupdate.sh will call is M7_sysUpdater.py
For this purpose, the "self extracting file" concept is used and installer.bin is created in which
the original zip is embedded.


as of this writing this file should be in 1.2.7.13 release
so in the 1.2.7.13 release a zip file would contain
a. installer.bin
b. 1.2.7.13 manifest file
c. 1.2.7.13 checksum file
d. M7_sysUpdater.py [which is this file]

this file will just call the installer.bin
installer.bin extracts the zip file from itself, installs the libraries, runs the python updater
which is used be this file(M7_sysUpdater.py) and renamed as actualupdater.py

"""

logbasename="preupdate.log"

def main():
#M7_fwupdate.sh extracted the zip file into tmp_fw_update directory
#just call the installer.bin file to start the installation
    
#create the logfile in non-volatile partition
    nvlogging  = logfiles.SetLogging(logbasename)
    nvlogging.CheckNVMount()
    logprefix = nvlogging.GetPrefix()
    logpath = logprefix + "/" + logbasename
    errorlog = "sysupdateerror.log"
#could be in JFFS2 or the mmcblk0p3 partition
    LOGFILE=open(logpath, "w+")


    LOGFILE.write("starting the updater which will call the installer \n")
    installer = glob.glob("tmp_fw_update/*.bin")
#there should be only one installer
#due to lack of space delete the original zip file
    cmd = "rm -rf *.zip;chmod +x %s;%s 2>%s/%s" % (installer[0], installer[0], logprefix, errorlog)
    LOGFILE.write("running cmd %s\n" % cmd)
    p1 = subprocess.Popen([cmd], shell=True)
    status = p1.wait()
    if status != 0:
        LOGFILE.write("%s fail \n" % cmd)
        return -1



# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
    main()
    
