/*************
 *
 * Filename:    fwDld_9x00.c
 *
 * Purpose:     Contains routines needed to update MDM 9x00 based devices
 *
 * Copyright: © 2013 Sierra Wireless Inc., all rights reserved
 *
 **************/
#include "fwDld_9x00.h"

static BOOL fwdwlcomplete = FALSE;
static BOOL fwdwfail = FALSE;
/*
 * Name:     FwDwldCbk_9x00
 *
 * Purpose:  Firmware download completion callback
 *
 * Return:   None
 *
 * Notes:    none
 */
void FwDwldCbk_9x00(ULONG status)
{
    if (0 == status)
    {
        fprintf( stderr, "\nINFO: Firmware download complete; waiting for device...\n" );
    }
    else
    {
        fwdwfail = TRUE;
    }

    /* Unsubscribe from the callback */
    SetFwDldCompletionCbk(NULL);
    fwdwlcomplete = TRUE;
}

/*
 * Name:     FwDloader_9x00
 *
 * Purpose:  Download an image to a MDM 9x00 based device
 *
 * Return:   None
 *
 * Notes:    none
 */
void FwDloader_9x00( CHAR *pImagePath )
{
    ULONG rc;
    CHAR completeImagePath[512];
    ULONG len = 0;

    /* Reset the firmware download completion and device ready flags */
    fwdwlcomplete = FALSE;
    fwdwfail = FALSE;

    rc = SetFwDldCompletionCbk( FwDwldCbk_9x00 );
    if( eQCWWAN_ERR_NONE != rc )
    {
        fprintf( stderr, "ERROR: Failed to register firmware Download Completion Callback\n"\
                         "Failure Code: %ld\n", rc );
        exit(0);
    }

    /* Concatenate image Path with file name */
    memset( completeImagePath, 0, sizeof(completeImagePath) );
    strncpy( completeImagePath,
             pImagePath,
             strlen(pImagePath) );
    len = strlen(completeImagePath);
    CHAR *pr = &completeImagePath[len - 1];
    if( *pr != '/' )
        *(pr + 1) = '/';

    /* Start downloading the firmware */
    rc = UpgradeFirmware2k( completeImagePath );
    if( eQCWWAN_ERR_NONE != rc )
    {
        /* some firmware of MC7700 may reboot immediately after receiving
         * set firmware id command without sending out respond,
         * neglect this error to bypass issue*/
        if(eQCWWAN_ERR_NO_DEVICE !=rc )
        {
            fprintf( stderr, "Firmware Download Failed\n"\
                             "Failure Code: %ld\n", rc );
            exit(0);
        }
        return;
    }

    fprintf( stderr, "\n\nDownloading Firmware");
    while( !fwdwlcomplete )
    {
        /* Display "." while firmware downloads */
        fprintf( stderr, ".");
        sleep(2);
    }

    if (fwdwfail)
    {
        fprintf( stderr, "ERROR: Firmware Download Failed\n");
        exit(0);
    }

    /* Give the firmware time to apply any additional CWE files that are
     * not firmware boot and/or application images
     */
    fprintf(stderr, "INFO: Applying SPKG updates - please wait 20 seconds...\n\n");
    sleep(20);

    fprintf( stderr, "INFO: Firmware Download Succeeded\n");
}
