#!/bin/bash

#Usage : ./sign_deb_package deb_path key_path crt_path
deb_path=$1
key_path=$2
crt_path=$3

if [ ! -f "$deb_path" ]; then
    echo "deb_path : $deb_path is not exit"
    exit 0
fi

out_path=/tmp/tmp_deb_decompress_path
if [ -d $out_path ];then
    rm -rf $out_path
fi
mkdir $out_path


fakeroot dpkg-deb -R $deb_path $out_path

#sign elfs
function sign_elfs() {
    for element in `ls $1`; do
        dir_or_file=$1/$element
        if [ -d $dir_or_file ]; then
           sign_elfs $dir_or_file
        else
            if file $dir_or_file | grep -i ELF; then
                echo $dir_or_file
                deepin-elf-sign $dir_or_file $key_path $crt_path
                if [ $? != 0 ]; then
                    echo "fatal error!"
                    exit -1
                fi
             fi
        fi
    done
}

sign_elfs $out_path

#compress
out_deb=./signed_deb
if [ ! -d $out_deb ];then
    mkdir $out_deb
fi
fakeroot dpkg-deb -b $out_path $out_deb
