#!/bin/bash
upgrade_patch=/etc/cpeagent/upgrade/
patch_name=PATCH-X86-THIRD-0.0.8
PWD=`pwd`

target_file=(
$upgrade_patch/$patch_name/$patch_name.tar.gz
$upgrade_patch/$patch_name/$patch_name.sh
$upgrade_patch/$patch_name/package/httpd-2.4.56-2.codeit.el7.x86_64.rpm
$upgrade_patch/$patch_name/package/httpd-devel-2.4.56-2.codeit.el7.x86_64.rpm
$upgrade_patch/$patch_name/package/httpd-filesystem-2.4.56-2.codeit.el7.noarch.rpm
$upgrade_patch/$patch_name/package/httpd-tools-2.4.56-2.codeit.el7.x86_64.rpm
$upgrade_patch/$patch_name/package/mod_ssl-2.4.56-2.codeit.el7.x86_64.rpm
$upgrade_patch/$patch_name/package/openssl-quic-libs-3.0.8-1.codeit.el7.x86_64.rpm
$upgrade_patch/$patch_name/package/pcre2-10.23-2.el7.x86_64.rpm
)

target_md5=(
"7f862bf1266d003a99b0535f1c1bf73f"
"abf6749bf1c79e29bd239531bb669615"
"47e1dfe9f23c5cc2eb26309bb50736b1"
"4ee9ce8515607e1dbc075ee99f07e2d4"
"281c4540950f24d6add0af90bd74a187"
"84f083e37150f46cd6b26e53ad457367"
"526fc8df85647c3b6b4a04326562421c"
"da76bc878416f69260fa50a684e50251"
"2ef628d8ae7bf136d651a2def8fe9d2e"
)

md5_check()
{
    local md5=$(md5sum $1 | awk '{print $1}')
    if [ "$md5" != "$2" ];then
        echo "Check $1 md5 failed, expect $2 actual $md5"
        exit 1
    fi
}

if [ ! -f $patch_name.tar.gz ];then
    echo "Could not find $patch_name.tar.gz under current dir $PWD"
    exit 1
fi

md5_check $patch_name.tar.gz "7f862bf1266d003a99b0535f1c1bf73f"

if [ ! -d $upgrade_patch/$patch_name ]; then
    mkdir -p $upgrade_patch/$patch_name || {
        echo "mkdir $upgrade_patch/$patch_name failed"
        exit 1
    }
fi

echo "coping file ..."
cp $patch_name.tar.gz $upgrade_patch/$patch_name -f || {
    echo "cp $patch_name.tar.gz to $upgrade_patch/$patch_name failed"
    exit 1
}
echo "copy file success"

echo "drpressing tarball ..."
tar -xzvf $upgrade_patch/$patch_name/$patch_name.tar.gz -C $upgrade_patch/$patch_name || {
    echo "depress $patch_name.tar.gz failed"
    exit 1
}
echo "drpress tarball success"

echo "checking md5 ..."
for((i=0;i<${#target_file[@]};i++));
do
    md5_check ${target_file[i]} ${target_md5[i]}
done
echo "check md5 success"

echo "installing patch ..."
$upgrade_patch/$patch_name/$patch_name.sh install || {
    echo "install patch failed, ret $?"
    exit 1
}
echo "install patch success"

echo "checking httpd service status..."
systemctl status httpd || {
    echo "httpd service abnormal"
    exit 1
}
echo "check httpd service status success"

echo "0.0.8" > /etc/cpeagent/PATCH-THIRD-VERSION
echo "====================="
echo "Manual install patch success"
echo "====================="
