#!/bin/sh

set -e

# Generate distro-info CSV
echo "version,codename,series,created,release,eol" > /usr/share/distro-info/lingmo.csv
echo "5.0,Unstable,unstable,2021-06-01" >> /usr/share/distro-info/lingmo.csv

# Generate os-version from base-files' os-release at install time
generate_os_version() {
    local TEMPLATE="/usr/share/lingmo/os-version.in"
    local OUTPUT="/etc/os-version"
    local OS_RELEASE="/etc/os-release"

    if [ ! -f "$TEMPLATE" ]; then
        echo "WARNING: $TEMPLATE not found, skipping os-version generation" >&2
        return
    fi

    if [ ! -f "$OS_RELEASE" ]; then
        echo "WARNING: $OS_RELEASE not found, skipping os-version generation" >&2
        return
    fi

    # Read values from base-files' os-release
    local DISTRO_NAME VERSION BUILD_VER
    DISTRO_NAME=$(grep '^NAME=' "$OS_RELEASE" | cut -d'"' -f2)
    VERSION=$(grep '^VERSION=' "$OS_RELEASE" | cut -d'"' -f2)
    BUILD_VER=$(grep '^BUILD=' "$OS_RELEASE" | cut -d'"' -f2)

    # Fallback: try system/release for BUILD_VER if not in os-release
    if [ -z "$BUILD_VER" ] && [ -f "/system/release" ]; then
        BUILD_VER=$(grep '^BUILD=' "/system/release" | cut -d'"' -f2)
    fi

    # Generate os-version by replacing placeholders
    sed -e "s|@@DISTRO_NAME@@|${DISTRO_NAME}|g" \
        -e "s|@@VERSION@@|${VERSION}|g" \
        -e "s|@@BUILD_VER@@|${BUILD_VER:-unknown}|g" \
        "$TEMPLATE" > "$OUTPUT"
}

case "${1}" in
	configure)
	    update-alternatives --install /etc/deepin-version \
		    deepin-version /usr/lib/deepin/desktop-version 50

	    # Generate os-version from base-files data
	    generate_os_version

	    if [ -x /usr/sbin/update-initramfs ]
	    then
		    update-initramfs -u
	    fi

        if [ -x /usr/sbin/update-grub ]
        then
            /usr/sbin/update-grub || echo "update-grub failed! Ignore..." >&2
        fi
		;;

	abort-upgrade|abort-remove|abort-deconfigure)

		;;

	*)
		echo "postinst called with unknown argument \`${1}'" >&2
		;;
esac

#DEBHELPER#

exit 0
