#!/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 log partition begin"
if [ "$(uname -m)" != "aarch64" ] ;then
	exit 0
fi

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

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

if [ ! -d "/var/log"]; then
    mkdir -p "/var/log"
fi

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

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

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

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

echo "Recover log partition end"
