#!/bin/bash
# filepath: check_deb_installed.sh

if [ $# -eq 0 ]; then
    echo "Usage:  <check_dir>"
    exit 1
fi

check_dir=$1
cd "$check_dir"

TEMP_DIR=$(mktemp -d)
for deb in *.deb; do
    pkg=$(dpkg-deb -f "$deb" Package 2>/dev/null)
    if [ -z "$pkg" ]; then
        echo "$deb: 无法解析包名"
        continue
    fi
    cur_ver=$(dpkg -l "$pkg"| grep  "$pkg"|awk '{print $3}')
    #找不到或版本对不上都安装
    deb_ver=$(printf $(echo -n $deb | sed 's/\\/\\\\/g;s/\(%\)\([0-9a-fA-F][0-9a-fA-F]\)/\\x\2/g')|awk -F "_" '{print $2}')
    if [ -z "$cur_ver" ] || [ "$cur_ver" != "$deb_ver" ]; then
        echo "$deb: $pkg $cur_ver != $deb_ver"
        cp "$deb" $TEMP_DIR
    fi
done

cnt="$(ls -l $TEMP_DIR | wc -l)"

if [ $cnt -gt 1 ]; then
    fs=`ls  $TEMP_DIR`
    printf "\n将安装以下驱动依赖包:\n$fs\n"
    sudo dpkg -i $TEMP_DIR/*.deb
fi

rm -rf $TEMP_DIR