#!/bin/bash

UPDATER_PROGRESS_NAME=(
  "/opt/update-module/current/usr/share/kylin-system-updater/kylin-system-updater"
  "/usr/share/kylin-system-updater/kylin-system-updater"
)

if [ ! -d /var/cache/kylin-system-updater ];then
    mkdir -p /var/cache/kylin-system-updater
fi

if [ ! -d /var/cache/kylin-system-updater/json ];then
    mkdir -p /var/cache/kylin-system-updater/json
fi

if [ ! -f /var/cache/kylin-system-updater/kylin-system-updater.db ];then
    echo "Copying database to the specified path ..."
    cp -r /usr/share/kylin-system-updater/kylin-system-updater.db  /var/cache/kylin-system-updater/
fi
if [ ! -d /var/log/kylin-unattended-upgrades ];then
    mkdir -p /var/log/kylin-unattended-upgrades
fi
if [ -f /var/lib/unattended-upgrades/unattended-upgrade.conf ];then
	echo "unattended-upgrade.conf exists,removing..."
	rm /var/lib/unattended-upgrades/unattended-upgrade.conf
fi

if [ -f /usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py ];then
    # echo "Database record migration"
    # /usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py -m
    /usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py -u appname_cn=
    /usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py -t=tid_search
    /usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py -u status_cn=
    /usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py -u changelog=
    /usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py -f init_version="yes"
fi

for path in "${UPDATER_PROGRESS_NAME[@]}"; do
  pid=$(pgrep -f "$path")
  if [ -n "$pid" ]; then
    echo "Running process: $path (PID: $pid),Killing $pid..."
    kill $pid || true
  fi
done

chmod +x /usr/bin/check_config_file.py
/usr/bin/check_config_file.py

QUIT_STRATEGIES_SERVICE="/usr/share/kylin-system-updater/SystemUpdater/Core/quitStrategiesService.py"
if [ -x "$QUIT_STRATEGIES_SERVICE" ]; then
    echo "Kylin-strategies-servic restart..."
    "$QUIT_STRATEGIES_SERVICE" || true
fi

systemctl enable kylin-unattended-upgrades.service
systemctl restart kylin-unattended-upgrades.service || true
