' noreboot
' restart
' reboot - (default)
Function UpdatePackage(commandId as String, packageUrl as String, reboot as String)
    if m.appspaceGlobal.isAppUpdateEnabled = true then
        SendUpdate({
            id: commandId,
            message: "Please use the new Software Updates features in the Devices extension to manage BrightSign app updates. The Device Task has been blocked to avoid conflicts",
            result: false
        })
        return false
    end if

    ' skip updating if is in progress
    if m.appspaceGlobal.updating = true then
        SendUpdate({
            id: commandId,
            message: "Update already in progress."
            result: false
        })
        return false
    end if

    ' global for tmp
    m.appspaceGlobal.updating = true
    m.appspaceGlobal.tmpPath = "/tmp"
    downloadFile = m.appspaceGlobal.tmpPath + "/autorun.zip"
    createDirectory(m.appspaceGlobal.tmpPath)
    ' callback
    options = {
        callback: "UpgradePackage",
        options: {
            commandId: commandId,
            tmpPath: m.appspaceGlobal.tmpPath
            downloadFile: downloadFile,
            reboot: reboot
        }
    }

    ' download
    DownloadUrl(commandId, packageUrl, downloadFile, options)

End Function
'''''''''''''''''''''''''''
Function UpdateFirmware(commandId as String, packageUrl as String)
    ' skip updating if is in progress
    if m.appspaceGlobal.updatingFirmware = true then
        SendUpdate({
            id: commandId,
            message: "Firmware update already in progress."
            result: false
        })
        return false
    end if

    ' global for tmp
    m.appspaceGlobal.updatingFirmware = true
    m.appspaceGlobal.tmpPath = "/tmp"

    ' append tmppath with timestamp
    date = CreateObject("roSystemTime").GetLocalDateTime()
    epochTime = date.ToSecondsSinceEpoch().toStr()
    tmpAppPath = m.appspaceGlobal.tmpPath + "/fw_" + epochTime
    downloadFile = tmpAppPath + ".zip"
    createDirectory(m.appspaceGlobal.tmpPath)

    ' callback
    options = {
        callback: "UpgradeFirmware",
        options: {
            commandId: commandId,
            downloadFile: downloadFile,
            tmpAppPath: tmpAppPath,
            reboot: "reboot"
        }
    }
    NotifyUpdateProgress(options.commandId, "Downloading firmware file")
    ' download
    DownloadUrl(commandId, packageUrl, downloadFile, options)

End Function
'''''''''''''''''''''''''''
Function CancelUpdatePackage()
    m.appspaceGlobal.updating = false
End Function
'''''''''''''''''''''''''''
Function CancelUpdateFirmware()
    m.appspaceGlobal.updatingFirmware = false
End Function
'''''''''''''''''''''''''''
Function NotifyUpdateProgress(id, message)
    SendUpdate({
        id: id,
        message: message
    })
End Function
'''''''''''''''''''''''''''
Function UpgradePackage(options) As Void
    ' status updated
    NotifyUpdateProgress(options.commandId, "Downloaded update package.")

    downloadFile = options.downloadFile
    reboot = options.reboot
    tmpPath = options.tmpPath
    tmpUnpackPath = tmpPath + "/unpack/"

    NotifyUpdateProgress(options.commandId, "Verifying package")
    if Unpack(downloadFile, tmpUnpackPath) = false then
        SendUpdate({
            id: options.commandId,
            message: "Failed to unzip firmware file.",
            result: false
        })
        return
    end if

    NotifyUpdateProgress(options.commandId, "Coyping autorun.zip file to root folder.")
    MoveFile(downloadFile, "/autorun.zip")

    NotifyUpdateProgress(options.commandId, "Cleaning up tmp folder.")
    DeleteDirectory(tmpPath)

    ' create a backup folder
    CreateDirectory("/autorun-backup")
    CopyFile("/autorun.brs", "/autorun-backup/autorun.brs")

    NotifyUpdateProgress(options.commandId, "Removing autorun.brs file.")
    DeleteFile("/autorun.brs")

    ' update successfully
    SendUpdate({
        id: options.commandId,
        result: true
    })

    ' reboot or return value
    ' test restart script
    if reboot = "noreboot" then
        m.appspaceGlobal.updating = false
    else if reboot = "restart" then
        NotifyUpdateProgress(options.commandId, "Restarting.")
        sleep(3000)
        RestartScript()
    else
        NotifyUpdateProgress(options.commandId, "Rebooting.")
        sleep(3000)
        ' default to reboot system
        RebootDevice()
    end if

End Function
'''''''''''''''''''''''''''
Function UpgradeFirmware(options)
    ' status updated
    NotifyUpdateProgress(options.commandId, "Firmware package downloaded")

    '
    downloadFile = options.downloadFile
    tmpAppPath = options.tmpAppPath
    reboot = options.reboot

    ' unzip
    NotifyUpdateProgress(options.commandId, "Unzipping firmware package")
    if Unpack(downloadFile, tmpAppPath) = false then
        SendUpdate({
            id: options.commandId,
            message: "Failed to unzip firmware file.",
            result: false
        })
    end if

    ' check extracted zip that sometime contains folder
    dirs = ListDir(tmpAppPath)
    if dirs.count() = 1 then
        dirPath = tmpAppPath + "/" + dirs[0] + "/"
        checkDir = CreateObject("roReadFile", dirPath)
        ' check is directory
        if type(checkDir) = "roReadFile" then
            tmpAppPath = tmpAppPath + "/" + dirs[0]
        endif
    end if

    ' get the firmware file
    dirs = MatchFiles(tmpAppPath,"*.bsfw")
    filename = dirs[0]

    ' move firmware file from tmp to root of sd card
    NotifyUpdateProgress(options.commandId, "Copy file to root")
    MoveFile(tmpAppPath + "/" + filename, "/" + filename)

    ' clean up
    NotifyUpdateProgress(options.commandId, "Cleaning up")
    DeleteFile(downloadFile)
    DeleteDirectory(options.tmpAppPath)

    m.appspaceGlobal.updatingFirmware = false

    NotifyUpdateProgress(options.commandId, "Rebooting")
    sleep(1000)
    ' update successfully
    SendUpdate({
        id: options.commandId,
        result: true
    })
    ' need to do this to ensure success message above sent back to the caller
    NotifyUpdateProgress(options.commandId, "10 second to reboot")
    sleep(1000)
    NotifyUpdateProgress(options.commandId, "9 seconds to reboot")
    sleep(1000)
    NotifyUpdateProgress(options.commandId, "8 seconds to reboot")
    sleep(1000)
    NotifyUpdateProgress(options.commandId, "7 second to reboot")
    sleep(1000)
    NotifyUpdateProgress(options.commandId, "6 seconds to reboot")
    sleep(1000)
    NotifyUpdateProgress(options.commandId, "5 seconds to reboot")
    sleep(1000)
    NotifyUpdateProgress(options.commandId, "4 second to reboot")
    sleep(1000)
    NotifyUpdateProgress(options.commandId, "3 seconds to reboot")
    sleep(1000)
    NotifyUpdateProgress(options.commandId, "2 seconds to reboot")
    sleep(1000)
    NotifyUpdateProgress(options.commandId, "1 second to reboot")
    sleep(1000)
    ' default to reboot system
    RebootDevice()

End Function
'''''''''''''''''''''''''''
Function Unpack(zipFile as String, tmpAppPath as String)
    createDirectory(tmpAppPath)
    package = CreateObject("roBrightPackage", zipFile)
    package.Unpack(tmpAppPath)

    ' get failure reason
    if package.GetFailureReason() = "" then
        return true
    end if
    return false
End Function
'''''''''''''''''''''''''''
Function SendUpdate(event)
    m.appspaceGlobal.htmlWidget.PostJSMessage(event)
End Function