#!/bin/bash

UPDATE_INFO="/var/lib/lastore/update_infos.json"

function prepare()
{
    # The unit is typically launched by apt hooks,
    # so we just directly exit failed when the apt-get is still running, and restart it after 1 seconds.
    if /usr/bin/pgrep apt-get > /dev/null; then
        echo "apt-get is running, please try it later"
        exit 1;
    fi

    if [ "$(/usr/bin/busctl get-property com.deepin.lastore /com/deepin/lastore com.deepin.lastore.Manager SystemOnChanging)" != "b false" ]; then
        echo "system is on changing, please try it later"
        exit -1;
    fi
}

function systemd_build_system_info()
{
    systemctl start lastore-build-system-info.service
}

function build_system_info_now()
{
    /usr/bin/lastore-tools update -j=update_infos -output=$UPDATE_INFO
    /usr/bin/lastore-tools update -j=desktop -o /var/lib/lastore/
    /var/lib/lastore/scripts/build_safecache.sh > /dev/null
}

#We should clean the update_infos.json early, otherwise
#actions, like systemctl stop, reboot immediately after apt-get
#would cause the update_infos.json invalid.
[ -f $UPDATE_INFO ] && rm $UPDATE_INFO

case "$1" in
    "-now")
        prepare
        build_system_info_now
        ;;
    *)
        if [[ -S /var/run/systemd/notify ]]; then
            systemd_build_system_info
        else
            build_system_info_now
        fi
        ;;
esac
sync