#!/usr/bin/python3
# -*- coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# Copyright (C) 2025 UBports Foundation
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUTa
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Authored by: Ratchanan Srirattanamet <ratchanan@ubports.com>

import sys

from gi.repository import Gio

# Note: once settings is written by Lomiri, it will always convert
# application:// and appid://<pkg>/<app>/current-user-version to
# appid://<pkg>.<app> format.
# https://gitlab.com/ubports/development/core/lomiri/-/blob/0.5.0/plugins/Lomiri/Launcher/gsettings.cpp?ref_type=tags#L63
#
# Note: Click app migration is handled by Click itself.
# https://gitlab.com/ubports/development/core/click/-/blob/0.5.2/click_package/commands/migrate.py?ref_type=tags#L56

RENAMED_APP_MAP = {
    "appid://dialer-app": "appid://lomiri-dialer-app",
    "appid://messaging-app": "appid://lomiri-messaging-app",
    "appid://address-book-app": "appid://lomiri-addressbook-app",
    "appid://ubuntu-system-settings": "appid://lomiri-system-settings",
}


def main():
    launcher_settings = Gio.Settings.new("com.lomiri.Shell.Launcher")
    items_v = launcher_settings.get_user_value("items")

    if items_v is None:
        print(
            "User has never added/removed launcher items. Default value is "
            "migrated automatically."
        )
        return 0

    items = items_v.get_strv()
    items_mapped = [RENAMED_APP_MAP.get(item, item) for item in items]

    if launcher_settings.set_strv("items", items_mapped):
        print("Launcher items for system apps updated.")
        return 0
    else:
        print("Unable to set launcher items. (key is not writable?)")
        return 1


if __name__ == "__main__":
    sys.exit(main())
