#youtube_dl/update.py: A hack-a-day fix for the updater; at least now it's looking for the right software

import hashlib

def getLatestVersion(text, verbose, to_screen):
    # Check if there is a new version
    try:
        newvpage = text.split(u"LATEST- ", 1)[1]
        return newvpage.split(u"</h")[0], newvpage
    except Exception:
        if verbose:
            to_screen(encode_compat_str(traceback.format_exc()))
        to_screen('ERROR: can\'t find the current version. Please try again later.')
        return None, None
    
def checkBadHash(newcontent):
    new_exe = newcontent.split(b'\n', 2)
    return str(new_exe[1][1:65]) != hashlib.sha256(new_exe[2]).hexdigest()

def update_self(to_screen, verbose, opener):
    """Update the program file with the latest version from the repository"""

    UPDATE_URL = "https://notabug.org/GPast/avideo/"
    VERSIONS_URL = UPDATE_URL + 'wiki/Downloads'

    if not isinstance(globals().get('__loader__'), zipimporter):
        to_screen('It looks like you installed youtube-dl with a package manager, setup.py or a tarball. Please use that to update.')
        return
    
    newversion, newvpage = getLatestVersion(opener.open(VERSIONS_URL).read().decode('utf-8'), verbose, to_screen)
    
    if newversion == None:
        return
    elif newversion == __version__:
        to_screen('youtube-dl is up-to-date (' + __version__ + ')')
        return
    to_screen('Updating to version ' + newversion + ' ...')
    #Parse the download URL of the executable zipfile
    vgetURL = newvpage.split("Executable Zip", 1)[0].rsplit("href=\"", 1)[1].split("\"", 1)[0]
    version = {'bin': [vgetURL]}
    
    filename = os.path.realpath(sys.argv[0])
    if not os.access(filename, os.W_OK):
        to_screen('ERROR: no write permissions on %s' % filename)
        return
