#!/bin/bash

PATCH_ROOT=`pwd`

if [ -f "$PATCH_ROOT/arch" ]; then  
    ENV_CPU_ARCH=`uname -m`
    ENV_PATCH_ARCH=`cat  $PATCH_ROOT/arch`
    if [[ -n $ENV_PATCH_ARCH ]] && [[ $ENV_CPU_ARCH != $ENV_PATCH_ARCH ]]; then
        echo "补丁架构与当前系统不一致"
        notify-send "错误" "补丁架构与当前系统不一致" --icon=$PATCH_ROOT/.mimedata/icon.png
        exit 1
    fi
fi

ls /tmp/kypatcher-working* 2>/dev/null
if [ $? -eq 0 ]; then  
    notify-send "错误" "补丁正在安装或回滚，请稍后再尝试打开。" --icon=$PATCH_ROOT/.mimedata/icon.png
    exit 10
fi

pgrep dpkg
if [ $? -eq 0 ]; then  
    notify-send "错误" "无法取得dpkg缓存锁，请稍后再试。" --icon=$PATCH_ROOT/.mimedata/icon.png
    exit 10
fi

pgrep apt
if [ $? -eq 0 ]; then  
    notify-send "错误" "无法取得dpkg缓存锁，请稍后再试。" --icon=$PATCH_ROOT/.mimedata/icon.png
    exit 11
fi

echo "正在检查补丁安装环境..."
install_ver=$(dpkg -s kypatcher 2>/dev/null | grep '^Version' | awk '{print $2}')
if [ -z "$install_ver" ]; then  
    install_ver="0"  
fi  
package_ver=$(dpkg-deb -f $PATCH_ROOT/.mimedata/kypatcher*.deb Version)
dpkg --compare-versions $install_ver lt $package_ver
if [[ $? -ne 1 ]];then
    echo "正在部署补丁安装环境..."
    if [ "$EUID" -ne 0 ]; then
        pkexec dpkg -i --force-confold $PATCH_ROOT/.mimedata/kypatcher*.deb &> /dev/null 2>&1
    else
        dpkg -i --force-confold $PATCH_ROOT/.mimedata/kypatcher*.deb &> /dev/null 2>&1
    fi

    if [ $? -ne 0 ]; then  
        notify-send "错误" "补丁打开失败，请稍后再尝试打开。" --icon=$PATCH_ROOT/.mimedata/icon.png
        exit 2  # 退出脚本并返回状态码1  
    fi 
fi

echo "唤起安装流程..."
trap "" SIGSEGV
nohup /etc/kypatcher/bin/kypi $PATCH_ROOT/cdrom  &> /dev/null 2>&1 &
sleep 1
exit 0
