#!/usr/bin/env python3

# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileContributor: Marco Trevisan <marco.trevisan@canonical.com>

from gi.repository import Gio

import sys


GNOME_SHELL_SETTINGS = "org.gnome.shell"
GNOME_SHELL_FAVORITE_APPS_KEY = "favorite-apps"

OLD_DESKTOP_ID = "yelp.desktop"
NEW_DESKTOP_ID = "org.gnome.Yelp.desktop"

def migrate_gnome_shell_favorite():
    settings = Gio.Settings.new(GNOME_SHELL_SETTINGS)
    if not settings.is_writable(GNOME_SHELL_FAVORITE_APPS_KEY):
        print("Can't migrate unity keys to GNOME Shell as they are not writable",
              file=sys.stderr)
        return

    favorite_apps = settings.get_strv(GNOME_SHELL_FAVORITE_APPS_KEY)

    try:
        favorite_apps[favorite_apps.index(OLD_DESKTOP_ID)] = NEW_DESKTOP_ID
    except ValueError:
        # Nothing to migrate
        return

    settings.set_strv(GNOME_SHELL_FAVORITE_APPS_KEY, favorite_apps)
    settings.sync() # force sync to avoid race


if __name__ == "__main__":
    source = Gio.SettingsSchemaSource.get_default()
    if not source.lookup(GNOME_SHELL_SETTINGS, True):
        print("GNOME Shell not installed: no migration needed")
        sys.exit(0)

    migrate_gnome_shell_favorite()
