#!/bin/bash

#set -x

#batchUpgrade

dbusServerOk=`systemctl status dbus.service 2>/dev/null |grep -v grep |grep Active |grep active|wc -l`;
if [ "$dbusServerOk" == "0" ];then
    #dbus服务没有启动则正常退出。
    exit 0;
fi


# Update Custom Sources List Directory
APPSTORE_LIST="/var/lib/deepin-home-appstore-daemon/sources.list.d/appstore.list"
SOURCES_LIST="/var/lib/deepin-home-appstore-daemon/sources.list"

if [ ! -f "$APPSTORE_LIST" ] ; then
if [ ! -f "$SOURCES_LIST" ] ; then
    dbus-send --system --print-reply --dest=com.home.appstore.daemon /appstore com.home.appstore.daemon.interface.UpdateSourceDir >> /dev/null 2>&1
fi
fi


dpkglastlog=$(cat /var/log/dpkg.log |tail -n 1)

time=$( grep  'startup packages configure' /var/log/dpkg.log | tail -n 1 |awk -F " " '{print $1"  "$2 }' )
#echo $time

dpkgSucess=$(echo "${dpkglastlog}" | grep  " status installed"|wc -l)
#echo $dpkgSucess

dpkgtime=$( grep  'startup archives install' /var/log/dpkg.log | tail -n 1 |awk -F " " '{print $1" "$2 }' )
dpkgtime=$(echo "$dpkgtime"|cut -c 1-15);
dpkgtime=$dpkgtime".:..";
#echo $dpkgtime

dpkgnameversionline=$(grep "$dpkgtime upgrade " /var/log/dpkg.log | tail -n 1)
if [ -z "$dpkgnameversionline" ] ; then
    dpkgnameversionline=`grep  "$dpkgtime install " /var/log/dpkg.log | tail -n 1`
fi
#echo $dpkgnameversionline

dpkgname=$(echo "$dpkgnameversionline" |awk -F " " '{print $4}'|awk -F ":" '{print $1 }')
#echo $dpkgname
dpkgversion=$(echo "$dpkgnameversionline" |awk -F " " '{print $6}')
#echo $dpkgversion
dpkgname=`echo $dpkgname | sed -e 's/^[ \t]*//g'`;
dpkgversion=`echo $dpkgversion | sed -e 's/^[ \t]*//g'`;

#startCount=$(cat /var/log/apt/history.log|tail -n 4 | grep -a "Start-Date: $time" | wc -l)
installCount=$(cat /var/log/apt/history.log|tail -n 4 | grep -a "Install:.*$dpkgname*" | wc -l)
#reinstallCount=$(cat /var/log/apt/history.log|tail -n 4 | grep -a "Reinstall:.*$dpkgname*" | wc -l)
#upgradeCount=$(cat /var/log/apt/history.log|tail -n 4 | grep -a "Upgrade:.*$dpkgname*" | wc -l)
#downgradeCount=$(cat /var/log/apt/history.log|tail -n 4 | grep -a "Downgrade:.*$dpkgname*" | wc -l)
#commandlineCount=`cat /var/log/apt/history.log|tail -n 4 | grep -a "Commandline:.*$dpkgname*" | wc -l`

dpkginsttime=$(echo "$dpkgnameversionline" | cut -c 1-19)
installtimestamp=$(date -d "$dpkginsttime" +%s)
aptEndDate=$(grep "End-Date: " /var/log/apt/history.log | tail -n 1 | awk -F " " '{print $2,$3}')
enddatetimestamp=$(date -d "$aptEndDate" +%s)

if [ "$installCount" == "0" -a $[$installtimestamp] -gt $[$enddatetimestamp] -a $dpkgSucess -gt 0 ] ; then
    #echo "--a---a---";

    dpkgrmtime=$(grep "remove $dpkgname" /var/log/dpkg.log | tail -n 1 | awk -F " " '{print $1" "$2}')
    removetimestamp=$(date -d "$dpkgrmtime" +%s)
    if [ -z "$dpkgrmtime" ] ; then
        removetimestamp=0
    fi

    if [ $[$installtimestamp] -gt $[$removetimestamp] ] ; then
        dbus-send --system --print-reply --dest=com.home.appstore.daemon /appstore com.home.appstore.daemon.interface.SlotPackageOperationFromHook string:"$dpkgname" string:"$dpkgversion" string:'install37' >> /dev/null 2>&1
    fi

fi

########################


if [ -f "/var/log/apt/history.log" -a -f "/var/log/dpkg.log" ]; then

startCount=$(cat /var/log/apt/history.log | grep -a "Start-Date:" | wc -l)

if [ "$startCount" == "1" ]; then
   echo " " ;
    #/usr/bin/deepin-app-store-pkgcache -c
else

aptlasttime=$(cat /var/log/apt/history.log |tail -n 1)
checkDate=$(echo "${aptlasttime}" | grep -a "End-Date" | wc -l)

if [ "$checkDate" == "0" ]
then
	case $DPKG_HOOK_ACTION in
	install|unpack|remove|purge)

    	lastCmdLine=$(cat /var/log/apt/history.log |grep -an 'Commandline:'| tail -n 1 | cut -d':' -f1)
    	lastInstallLine=$(cat /var/log/apt/history.log |grep -an 'Install:'| tail -n 1 | cut -d':' -f1)
    	lastRemoveLine=$(cat /var/log/apt/history.log |grep -anE 'Remove:'| tail -n 1 | cut -d':' -f1)
    	lastUpgradeLine=$(cat /var/log/apt/history.log |grep -anE 'Upgrade:'| tail -n 1 | cut -d':' -f1)
    	lastDowngradeLine=$(cat /var/log/apt/history.log |grep -anE 'Downgrade:'| tail -n 1 | cut -d':' -f1)
    	lastReinstallLine=$(cat /var/log/apt/history.log |grep -anE 'Reinstall:'| tail -n 1 | cut -d':' -f1)
    	lastPurgeLine=$(cat /var/log/apt/history.log |grep -anE 'Purge:'| tail -n 1 | cut -d':' -f1)

    	if [[ $lastUpgradeLine -gt $lastCmdLine ]]
    	then
        	pkginstall=$(cat /var/log/apt/history.log |grep -aE 'Upgrade:'| tail -n 1 | sed 's/Install://g' | sed 's/Upgrade://g' | sed 's/Downgrade://g')
    		i=0
		pkgtmp=""
		for pkginfolist in $(echo $pkginstall | grep -Po '(.*?) \((.*?), (.*?)\)'); do
		if [[ i -eq 0 || i%4 -eq 0 ]];then
		pkgtmp="${pkginfolist}"
  		fi
  		if [[ i%4 -eq 2 ]];then

		IFS=':' read -ra arrpkgname <<< "${pkgtmp}"
		IFS=')' read -ra arrversion <<< "${pkginfolist}"

		pkgname="${arrpkgname[0]}"
		pkgversion="${arrversion[0]}"

    		#/usr/bin/deepin-app-store-pkgcache -i $pkgname $pkgversion
		#echo "scx1=" $pkgname $pkgversion
		pkgname=`echo $pkgname | sed -e 's/^[ \t]*//g'`;
		pkgversion=`echo $pkgversion | sed -e 's/^[ \t]*//g'`;
		dbus-send --system --print-reply --dest=com.home.appstore.daemon  /appstore com.home.appstore.daemon.interface.SlotPackageOperationFromHook string:${pkgname} string:${pkgversion} string:'install103'  >> /dev/null 2>&1
  		fi
  		i=$((i+1))
		done
	fi

    	if [[ $lastDowngradeLine -gt $lastCmdLine ]]
    	then
        	pkginstall=$(cat /var/log/apt/history.log |grep -aE 'Downgrade:'| tail -n 1 | sed 's/Install://g' | sed 's/Upgrade://g' | sed 's/Downgrade://g')
  		i=0
		pkgtmp=""
		for pkginfolist in $(echo $pkginstall | grep -Po '(.*?) \((.*?), (.*?)\)'); do
	  	if [[ i -eq 0 || i%4 -eq 0 ]];then
	    	pkgtmp="${pkginfolist}"
  		fi
	  	if [[ i%4 -eq 2 ]];then

		IFS=':' read -ra arrpkgname <<< "${pkgtmp}"
		IFS=')' read -ra arrversion <<< "${pkginfolist}"

		pkgname="${arrpkgname[0]}"
		pkgversion="${arrversion[0]}"

    		#/usr/bin/deepin-app-store-pkgcache -i $pkgname $pkgversion

		#echo "scx2=" $pkgname $pkgversion
		pkgname=`echo $pkgname | sed -e 's/^[ \t]*//g'`;
		pkgversion=`echo $pkgversion | sed -e 's/^[ \t]*//g'`;
		dbus-send --system --print-reply --dest=com.home.appstore.daemon  /appstore com.home.appstore.daemon.interface.SlotPackageOperationFromHook string:${pkgname} string:${pkgversion} string:'install131'  >> /dev/null 2>&1
  		fi
  		i=$((i+1))
		done  	
  	fi	   
        
	if [[ $lastInstallLine -gt $lastCmdLine ]]
	then
		pkginstall=$(cat /var/log/apt/history.log |grep -a 'Install:'| tail -n 1 | sed 's/Install://g' | sed 's/Upgrade://g' | sed 's/Downgrade://g')
		IFS='),' read -ra ADDR <<< "$pkginstall"
		for arrAllDetail in "${ADDR[@]}"; do
			result=$(echo $arrAllDetail)
			if [[ "$result" != "" ]]
			then
				IFS='(' read -ra pkgversionArr <<< "${arrAllDetail}"
				IFS=':' read -ra pkgnameBase <<< ""${pkgversionArr[0]}
				pkgversion=${pkgversionArr[1]}
				pkgname=${pkgnameBase[0]}

				if [[ "${pkgname}" != "" && "$pkgversion" != "" ]]
				then
		#			/usr/bin/deepin-app-store-pkgcache -i ${pkgname} $pkgversion
		#echo "scx3=" $pkgname $pkgversion
		pkgname=`echo $pkgname | sed -e 's/^[ \t]*//g'`;
		pkgversion=`echo $pkgversion | sed -e 's/^[ \t]*//g'`;

		dbus-send --system --print-reply --dest=com.home.appstore.daemon  /appstore com.home.appstore.daemon.interface.SlotPackageOperationFromHook string:${pkgname} string:$pkgversion string:'install157'  >> /dev/null 2>&1

				fi
			fi
		done
	fi

    if [[ $lastRemoveLine -gt $lastCmdLine ]]
    	then
	   pkginstall=$(cat /var/log/apt/history.log |grep -a 'Remove:' | tail -n 1 | sed 's/Remove://g')

	   IFS=',' read -ra ADDR <<< "$pkginstall"
	   for arrAllDetail in "${ADDR[@]}"; do
		result=$(echo $arrAllDetail)
		  if [[ "$result" != "" ]] 
		  then
			IN=$arrAllDetail
			arrpkgname=$(echo $IN | tr ":" "\n")
			read -a pkgname <<< "${arrpkgname[0]}"
			pkgversion=$(echo $arrAllDetail | grep -Po '(?<=\().*(?=\))')

		#	/usr/bin/deepin-app-store-pkgcache -r $pkgname $pkgversion
		#echo "scx=remove" $pkgname $pkgversion
		pkgname=`echo $pkgname | sed -e 's/^[ \t]*//g'`;
		pkgversion=`echo $pkgversion | sed -e 's/^[ \t]*//g'`;
		dbus-send --system --print-reply --dest=com.home.appstore.daemon  /appstore com.home.appstore.daemon.interface.SlotPackageOperationFromHook string:${pkgname} string:${pkgversion} string:'remove130'  >> /dev/null 2>&1
    		  fi
	   done	
    fi

    if [[ $lastReinstallLine -gt $lastCmdLine ]]
    	then
	   pkginstall=$(cat /var/log/apt/history.log |grep -a 'Reinstall:' | tail -n 1 | sed 's/Reinstall://g')

	   IFS=',' read -ra ADDR <<< "$pkginstall"
	   for arrAllDetail in "${ADDR[@]}"; do
		result=$(echo $arrAllDetail)
		  if [[ "$result" != "" ]] 
		  then
			IN=$arrAllDetail
			arrpkgname=$(echo $IN | tr ":" "\n")
			read -a pkgname <<< "${arrpkgname[0]}"
			pkgversion=$(echo $arrAllDetail | grep -Po '(?<=\().*(?=\))')

			#/usr/bin/deepin-app-store-pkgcache -i $pkgname $pkgversion
		#echo "scx4=" $pkgname $pkgversion
		pkgname=`echo $pkgname | sed -e 's/^[ \t]*//g'`;
		pkgversion=`echo $pkgversion | sed -e 's/^[ \t]*//g'`;
		dbus-send --system --print-reply --dest=com.home.appstore.daemon  /appstore com.home.appstore.daemon.interface.SlotPackageOperationFromHook string:${pkgname} string:${pkgversion} string:'install205'  >> /dev/null 2>&1
    		  fi
	   done	
    fi

    if [[ $lastPurgeLine -gt $lastCmdLine ]]
    	then
	   pkginstall=$(cat /var/log/apt/history.log |grep -a 'Purge:' | tail -n 1 | sed 's/Purge://g')

	   IFS=',' read -ra ADDR <<< "$pkginstall"
	   for arrAllDetail in "${ADDR[@]}"; do
		result=$(echo $arrAllDetail)
		  if [[ "$result" != "" ]] 
		  then
			IN=$arrAllDetail
			arrpkgname=$(echo $IN | tr ":" "\n")
			read -a pkgname <<< "${arrpkgname[0]}"
			pkgversion=$(echo $arrAllDetail | grep -Po '(?<=\().*(?=\))')

		#	/usr/bin/deepin-app-store-pkgcache -r $pkgname $pkgversion
		#echo "scx1=remove" $pkgname $pkgversion
		pkgname=`echo $pkgname | sed -e 's/^[ \t]*//g'`;
		pkgversion=`echo $pkgversion | sed -e 's/^[ \t]*//g'`;
		dbus-send --system --print-reply --dest=com.home.appstore.daemon  /appstore com.home.appstore.daemon.interface.SlotPackageOperationFromHook string:${pkgname} string:${pkgversion} string:'remove176'  >> /dev/null 2>&1
    		  fi
	   done	
    fi

	;;
esac

else
	existEndDate=$(cat /var/log/apt/history.log | tail -n 1 |grep -a 'End-Date' | wc -l)

	if [ $existEndDate == "1" ]; then

	aptlasttime=$(cat /var/log/apt/history.log |tail -n 1)
	aptlasttime=$(sed 's#  # #' <<< "${aptlasttime}")
	dpkglasttime=$(cat /var/log/dpkg.log |tail -n 1 | awk '{print $1,$2}')

	case $DPKG_HOOK_ACTION in
	install|unpack)
	
	while read packageFullName version; 
	do
		oldIFS=$IFS
		IFS=':'
	   	read -a pkgname <<< "${packageFullName}"
	   	IFS=$oldIFS

       		#/usr/bin/deepin-app-store-pkgcache -i ${pkgname[0]} $version
		#echo "scx5=" $pkgname $pkgversion
		pkgname=`echo $pkgname | sed -e 's/^[ \t]*//g'`;
		pkgversion=`echo $pkgversion | sed -e 's/^[ \t]*//g'`;
		dbus-send --system --print-reply --dest=com.home.appstore.daemon  /appstore com.home.appstore.daemon.interface.SlotPackageOperationFromHook string:${pkgname} string:${pkgversion} string:'install259'  >> /dev/null 2>&1
	done < <(sed -n "/${aptlasttime}/, /*/p" /var/log/dpkg.log | grep -aE 'install |upgrade ' | awk '{print $4,$6}')
	;;
   	remove|purge)

	while read packageFullName version; 
	do
	   	oldIFS=$IFS
       		IFS=':'
	   	read -a pkgname <<< "${packageFullName}"
	   	IFS=$oldIFS

       		#/usr/bin/deepin-app-store-pkgcache -r ${pkgname[0]} $version
		#echo "scx2=remove" $pkgname $pkgversion
		pkgname=`echo $pkgname | sed -e 's/^[ \t]*//g'`;
		pkgversion=`echo $pkgversion | sed -e 's/^[ \t]*//g'`;
		dbus-send --system --print-reply --dest=com.home.appstore.daemon  /appstore com.home.appstore.daemon.interface.SlotPackageOperationFromHook string:${pkgname} string:${pkgversion} string:'remove223'  >> /dev/null 2>&1
	done < <(sed -n "/${aptlasttime}/, /*/p" /var/log/dpkg.log | grep -a 'remove ' | awk '{print $4,$5}')
	;;
	esac
	fi
fi

fi

else
	echo " ";
	#/usr/bin/deepin-app-store-pkgcache -u
fi



	 #写入四行空行
	 #echo -e "\n" >> /var/log/apt/history.log
	 #echo -e "\n" >> /var/log/apt/history.log


