// ==UserScript==
// @name        Gnome extension download
// @namespace   blah.blah
// @description Provide download links for extensions.gnome.org
// @include     https://extensions.gnome.org/extension/*
// @version     1
// @grant       none
// ==/UserScript==

window.addEventListener('DOMContentLoaded', createLinks, false);

function createLinks(e) {
    var details = document.getElementsByClassName('extension-details')[0];
    var dl = document.createElement('dl');
    details.appendChild(dl);
    var dt = document.createElement('dt');
    dl.appendChild(dt);
    dt.appendChild(document.createTextNode('Download for Gnome version'));
    var div = document.getElementsByClassName('extension single-page')[0];
    var uuid = div.getAttribute('data-uuid');
    var svm = div.getAttribute('data-svm');
    var json = JSON.parse(svm);
    var versions = Object.keys(json).sort(version_sort);
    for(var index=0, len=versions.length; index < len; index++) {
        var version = versions[index];
        var pk = json[version]["pk"];
        var dd = document.createElement('dd');
        dl.appendChild(dd);
        var a = document.createElement('a');
        dd.appendChild(a);
        var uri = "https://extensions.gnome.org/download-extension/" + uuid + ".shell-extension.zip?version_tag=" + pk;
        a.setAttribute('href', uri);
        a.appendChild(document.createTextNode(version));
    }
}
function version_sort(a, b) {
    var a_parts = a.split('.');
    var b_parts = b.split('.');
    for(var index=0, len=Math.min(a_parts.length, b_parts.length); index < len; index++) {
        if(parseInt(a_parts[index]) > parseInt(b_parts[index])) return(-1);
        if(parseInt(a_parts[index]) < parseInt(b_parts[index])) return(1);
    }
    return(0);
}