#!/usr/bin/python3
#
# Copyright (C) 2025, UBports Foundation.
# SPDX-License-Identifier: GPL-3.0-only
#
# A session-migration state file contains 2 things:
# - The timestamp of the last time a migration happens.
# - The list of migrations that has been run.
#
# session-migration checks modification time (mtime) of the script directory
# (/usr/share/session-migration/scripts) against the recorded timestamp.
# If the recorded timestamp is greater than the mtime, then migrations will not
# be considered at all.
#
# However, sometimes due to Android clock stuffs, the recorded timestamp
# can be far in the future, which prevent any migration from happening ever
# again. In that case, we reset the timestamp to 0 to force session-migration
# to consider migrations again.
#
# Since the state file also contain the list of done migration, this will not
# cause any migration that has run before to run again.
#
# I guess session-migration (or now user-session-migration) should record the
# directory's mtime instead of the current time, but for now it is what it is.

import time

from configparser import ConfigParser
from pathlib import Path

import xdg


def main():
    now_timestamp = time.time()

    dir = Path(xdg.BaseDirectory.xdg_data_home)
    for file in dir.glob("session_migration-*"):
        config = ConfigParser()
        config.read(file)

        try:
            # ConfigParser always operates on strings.
            state_timestamp = float(config["State"]["timestamp"])
        except:
            # If timestamp is somehow not a number, there's nothing we can do.
            continue

        # I mean, this is an impossible state, is it?
        if state_timestamp > now_timestamp:
            config["State"]["timestamp"] = "0"
            with open(file, "w") as fp:
                config.write(fp)


if __name__ == "__main__":
    main()
