#!/bin/bash
# Package the firmware upgrade scripts in the IPMC and DATA areas.
# Copyright (c) 2024 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

set -e

#脚本作用:打包IPMC、DATA区升级固件脚本
#使用方法:
#
#
#包组成:1、conf.tar.gz 2、升级固件的升级文件
#
#调用本脚本的格式: packethpm.sh $1 $2 $3 $4 [$5]
#                 参数1:升级固件的升级文件
#                 参数2:升级固件对应的app区
#				  参数3:升级固件对应的配置区
#                 参数4:hpm包的配置文件
#                 参数5:conf.tar.gz 中的配置文件名,service包的话名字可能不一样,
#                       此参数可以不设置,不设置的话默认为:CfgFileList.conf
#

str_success="\033[32;1m[success]\033[0m"
str_fail="\033[31;1m[Fail]\033[0m"
APPHPM="ipmcimage.hpm"
IPMCFILE="ipmc.jffs2"
HPM="ipmc-crypt-image.hpm"
CONF="conf.tar.gz"

rm -rf *.hpm

#1、参数1判断需要打包的升级文件是否正确
if [ ! -f $1 ]
then
   echo ERROR:$1 file is not exist!
   exit 1
fi

#3、参数3确认support.tar.gz 配置文件
if [ -n $2 ]
then
   if [ ! -f CfgFileList.conf ]
   then
      echo ERROR:CfgFileList.conf is not exist!
      exit 1
   fi
   CFGFILELIST=CfgFileList.conf
else
   if [ ! -f $2 ]
   then
      echo ERROR:$2 is not exist!
      exit 1
   fi
   CFGFILELIST=$2
fi

#4、判断filesizecheck是否存在,这个文件是保证升级配置文件的正确性,比较重要
#二级流水线将构建安装在temp/tools下，请将filesizecheck所在目录添加到PATH环境变量

#5、判断脚本文件是否都存在
#确认beforeaction.sh
if [ ! -f beforeaction.sh ]
then
   echo ERROR:beforeaction.sh is not exist!
   exit 1
fi
chmod 550 beforeaction.sh
#确认afteraction.sh
if [ ! -f afteraction.sh ]
then
   echo ERROR:afteraction.sh is not exist!
   exit 1
fi
chmod 550 afteraction.sh

#确认update.cfg
if [ ! -f update.cfg ]
then
   echo ERROR:update.cfg is not exist!
   exit 1
fi

#7、校验support.tar.gz 中的配置文件为CfgFileList.conf或者为指定的参数3
filesizecheck $CFGFILELIST

#8、全部文件均ok后开始打包support.tar.gz
tar --format=gnu -czvf "$CONF" beforeaction.sh afteraction.sh $CFGFILELIST update.cfg

if [ -n "$HPM_ENCRYPT" ]; then
   crypto_tool encrypt "$CONF" "config.tar.gz" oaep
   mv "config.tar.gz" "$CONF"

   crypto_tool encrypt "$1" "$IPMCFILE" oaep
else
   mv "$1" "$IPMCFILE" 
fi

#9、打成整个包
hpmimage $2
chmod 444 $APPHPM

#文件签名此处移除,V5产品不再自签名
mv $APPHPM $HPM

#11、判断是否已生成包
if [ ! -f $HPM ]
then
   echo -e "create ipmc update file: $HPM ----> $str_fail"
   exit 1
else
   echo -e "create ipmc update file: $HPM ----> $str_success"
fi
