#! /usr/bin/python

import urllib.request
import sys, os

class UpdateModule:
    def __init__(self):
        self.de = "003-cinnamon"
        self.curDeVersion = self.getCurrentDEVersion()
        self.curMirror = self.getCurrentMirror()
        
        print("Current DE version: ", self.curDeVersion)
        print("Current mirror: ", self.curMirror)

        self.startDownload(self.curMirror + "/x86_64/current/bundles/.testing/003-cinnamon/version2.txt", "/tmp/version.txt")
        self.remoteDeVersion = self.getRemoteDEVersion()
        if self.remoteDeVersion > self.curDeVersion:
            print("Can Update")
        else:
            print("Up-to-date")
        
    def getRemoteDEVersion(self):
        filePath = "/tmp/version.txt"
        with open(filePath, mode = "r", encoding = "utf-8") as fd:
            return(fd.read())

    def getCurrentDEVersion(self):
        filePath = "/etc/porteus/" + self.de + ".ver"
        with open(filePath, mode = "r", encoding = "utf-8") as fd:
            fline = fd.read()
            return fline[:-1].split(':')[1]

    def getCurrentMirror(self):
        with open("/etc/porteus.conf", mode = "r", encoding = "utf-8") as fd:
            for fline in fd:
                if fline.startswith("SERVER="):
                    break;
            return fline[:-1].split('=')[1]

    def startDownload(self, url, filename):
        try: 
            urllib.request.urlretrieve(url, filename, self.reporthook)
          
        except Exception as e: 
            print(str(e))                     


    def reporthook(self, count, blockSize, totalSize):
        downloaded = count * blockSize
        if downloaded < totalSize:
            self.progress = downloaded/totalSize
            sys.stdout.write('\rDownloading %.2f%%' % (float(count * blockSize) / float(totalSize) * 100.0))
            sys.stdout.flush()
        else:
            sys.stdout.write('\rDownloading 100%  \n')
            sys.stdout.flush()
            self.progress = 1.0
            # os.system('/opt/porteus-scripts/update-porteus')
                    
            
updateModule = UpdateModule()
