#!/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.
    # build_system_info脚本改由updateSource后同步执行,因此无需判断apt-get进程是否存在
    #    if /usr/bin/pgrep apt-get > /dev/null; then
    #        echo "apt-get is running, please try it later"
    #        exit 1;
    #    fi

    if /usr/bin/pgrep build_system_info > /dev/null; then
        echo "build_system_info is running, please try it later"
        exit 1;
    fi

    if [ "$(/usr/bin/busctl get-property org.deepin.dde.Lastore1 /org/deepin/dde/Lastore1 org.deepin.dde.Lastore1.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
