#!/bin/sh

# SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
#
# SPDX-License-Identifier: LGPL-3.0-or-later

# Handle upgrade from 1.3.x
# Move system level linglong repository from old location to /var/lib/linglong
upgrade_from_1_3_x() {
        version=$1
        shift
        if dpkg --compare-versions "$version" ge "1.4.0"; then
                return
        fi
        echo "upgrade from 1.3.x"

        if [ -f /etc/X11/Xsession.d/21linglong ] &&
                [ "$(sha256sum /etc/X11/Xsession.d/21linglong)" = \
                        "5b82ac8e6b02cdae66294139e7db7cbe80af8cef6b0e2eddf8d509166afce544" ]; then
                rm /etc/X11/Xsession.d/21linglong
        fi

        if [ -d /var/lib/linglong ]; then
                echo "'/var/lib/linglong' directory exists."
                echo "Finish upgrading from 1.3.x without touch anything."
                return
        fi

        if [ ! -d /persistent/linglong ]; then
                echo "Old linglong repository not found."
                echo "Finish upgrading from 1.3.x without touch anything."
                return
        fi

        echo "Moving old deepin v23 linglong repository to new location..."
        mv /persistent/linglong /var/lib/linglong
        ln -s /var/lib/linglong /persistent/linglong # Quick fix for old files exported in old location.
        echo "Done"

        # This is good enough,
        # as linglong has only one repository publicly right now.
        echo "Removing old configuration file..."
        rm /var/lib/linglong/config.json -f
        echo "Done"
        return
}

upgrade_from_1_4_x() {
        version=$1
        shift
        if dpkg --compare-versions "$version" ge "1.5.0"; then
                return
        fi
        echo "upgrade from 1.4.x"

        if [ ! -d /var/lib/linglong/layers ]; then
                echo "Old data not found."
                echo "Finish upgrading from 1.4.x without touch anything."
                return
        fi

        echo "Backup old data..."
        oldPackageList="/var/lib/linglong/old-package.list"
        ls /var/lib/linglong/layers | grep -v "org.deepin.Runtime" >$oldPackageList
        oldData=$(mktemp --tmpdir=/var/lib/linglong -d old-data-XXXXXXXX)
        mv /var/lib/linglong/layers "$oldData"
        mv /var/lib/linglong/entries "$oldData"
        # chmod is for linglong-repair-tool.desktop(TryExec=$oldPackageList).
        chmod +x $oldPackageList
        chown deepin-linglong:deepin-linglong $oldPackageList
        chown -R deepin-linglong:deepin-linglong $oldData
}

case "$1" in
upgrade)
        upgrade_from_1_3_x $2
        upgrade_from_1_4_x $2
        ;;
abort-upgrade | abort-remove | abort-deconfigure) ;;
*)
        echo "postinst called with unknown argument '$1'" >&2
        exit 0
        ;;

esac

exit 0

# vi: ft=sh
