#! /bin/bash
 
# bios module init
chown secbox:secbox /data/trust/persistence.local/bios.db
chown secbox:secbox /data/backup

chown secbox:secbox /data/opt/currentvalue.json
chown secbox:secbox /data/opt/registry.json
chown secbox:secbox /data/opt/result.json
chown secbox:secbox /data/opt/setting.json
chown secbox:secbox /data/opt/SMBIOS_CONF
chown secbox:secbox /data/opt/SMBIOS_DIFF

APP_DEBUG_LOG_FILE=/var/log/app.log
FORMATTED_TIME=$(date + "%Y-%m-%d %T.%N" | awk -F. '{print $1 "." substr($2, 1, 6)}')
APP_NAME=bios
LOG_ERROR=ERROR
USER=secbox
MKDIR_COMMAND_FAILED="execute mkdir is failed"
CHOWN_COMMAND_FAILED="execute chown is failed"
FILE_IS_NOT_EXIST="bios file not exist"

#log format definition
app_log()
{
    # $1 is log level
    # $2 is error message
    # $3 is command status
    local message="$FORMATTED_TIME $APP_NAME $1: $2"
    # Check whether the third parameter is empty.
    if [ -n "$3" ]; then
        message="$message, status=$3"
    fi
    echo -e "$message" >> "$APP_DEBUG_LOG_FILE"
}

#module init
if [ ! -d /data/backup/bios ]; then
    app_log "$LOG_ERROR" "$FILE_IS_NOT_EXIST"
    # get result
    mkdir -p /data/backup/bios
    # get status
    status=$?
    if [ $status -ne 0 ]; then
        app_log "$LOG_ERROR" "$MKDIR_COMMAND_FAILED" "$status"
    fi
fi

if [ ! -d /data/opt/bmc/conf/bios ]; then
    app_log "$LOG_ERROR" "$FILE_IS_NOT_EXIST"
    # get result
    mkdir -p /data/opt/bmc/conf/bios
    # get status
    status=$?
    if [ $status -ne 0 ]; then
        app_log "$LOG_ERROR" "$MKDIR_COMMAND_FAILED" "$status"
    fi
fi

if [ ! -d /dev/shm/bios ]; then
    app_log "$LOG_ERROR" "$FILE_IS_NOT_EXIST"
    # get result
    mkdir -p /dev/shm/bios
    # get status
    status=$?
    if [ $status -ne 0 ]; then
        app_log "$LOG_ERROR" "$MKDIR_COMMAND_FAILED" "$status"
    fi
fi

# user is exists
id $USER >& /dev/null
status=$?
if [ $status -ne 0 ]; then
    app_log "$LOG_error" "$CHOWN_COMMAND_FAILED" "$status"
else
    #ranking drop
    chown -R secbox:secbox /data/backup/bios
    status=$?
    if [ $status -ne 0 ]; then
        app_log "$LOG_error" "$CHOWN_COMMAND_FAILED" "$status"
    fi

    chown -R secbox:secbox /data/opt/bmc/conf/bios
    status=$?
    if [ $status -ne 0 ]; then
        app_log "$LOG_error" "$CHOWN_COMMAND_FAILED" "$status"
    fi

    chown -R secbox:secbox /dev/shm/bios
    status=$?
    if [ $status -ne 0 ]; then
        app_log "$LOG_error" "$CHOWN_COMMAND_FAILED" "$status"
    fi
fi
