#!/bin/bash
# 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.

echo "Recover trust partition begin"
if [ "$(uname -m)" != "aarch64" ] ;then
	exit 0
fi

trustpart_sectors_num=$(busybox fdisk -l /dev/mmcblk0 | awk '/\/dev\/mmcblk0p7/ {print $6}')
if [ "$trustpart_sectors_num" != "524288" ] ;then
    sh /opt/bmc/script/partition_migrate.sh
fi

trustpart_sectors_num=$(busybox fdisk -l /dev/mmcblk0 | awk '/\/dev\/mmcblk0p7/ {print $6}')
if [ "$trustpart_sectors_num" != "524288" ] ;then
    exit 0
fi

mount | grep -i "/dev/mmcblk0p7"
if [ $? -eq 0 ] ;then
	exit 0
fi

if [! -d "/data/trust"]; then
    mkdir -p "/data/trust"
fi

for i in {1..3}; do
    /sbin/fsck.ext4 -f -y -v /dev/mmcblk0p7
    /bin/mount -t ext4  -rw /dev/mmcblk0p7 /data/trust
    if [ $? -ne 0 ]; then
        echo "check mount trust partition failed count $i"
    else
        echo "check mount trust partition successed"
        exit 0
    fi
done

echo "start format mount partition!"
/sbin/mkfs.ext4 /dev/mmcblk0p7 <<EOF
y
EOF
if [ $? -ne 0 ]; then
    echo "Recover trust partition failed(format trust partition failed)"
    exit 0
fi

/bin/umount /data/trust
/bin/mount -t ext4  -rw /dev/mmcblk0p7 /data/trust
if [ $? -ne 0 ]; then
    echo "Recover trust partition failed(mount trust partition failed)"
fi

echo "Recover trust partition end"
