#!/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.
process_name=$1
LOCK_FILE=/var/run/harbor_id.lock
FRAMEWORK_LOG_FILE=/var/log/framework.log

framework_log()
{
    echo -e `date  +"%Y-%m-%d %T"`" $1" >> $FRAMEWORK_LOG_FILE
}

if [ $# == 0 ];then
    framework_log "allocate harbor id failed because no process name is input"
    echo "please input a process name to allocate harbor id"
    exit 1
fi

if [ ! -e "$LOCK_FILE" ]; then
    touch $LOCK_FILE
fi

allocate_harbor_id() {
    i=1
    process_line_number=0
    first_blank_number=0
    last_nonblank_number=0
    harbor_id=0

    while read -r line; do
        if [ -z "$line" ]; then
            if [ $first_blank_number -eq 0 ]; then
                first_blank_number=$i
            fi
        else
            last_nonblank_number=$i
        fi

        if [ "$line" = "$process_name" ]; then
            process_line_number=$i
            sed -i "${i}s/.*//g" ${LOCK_FILE}
        fi

        i=`expr $i + 1`
    done < "$LOCK_FILE"

    if [ $i -lt 255 ]; then
        echo ${process_name} >> ${LOCK_FILE}
        harbor_id=`expr $i + 1`
        framework_log "allocate harbor id $harbor_id to $process_name"
        echo $harbor_id
        return 0
    fi

    if [ $first_blank_number -eq 0 ]; then
        if [ $process_line_number -eq 0 ]; then
            framework_log "allocate harbor id to $process_name failed"
            echo "allocate harbor id to $process_name failed"
        else
            sed -i "${process_line_number}s/.*/${process_name}/g" ${LOCK_FILE}
            harbor_id=`expr $process_line_number + 1`
            framework_log "allocate harbor id $harbor_id to $process_name"
            echo $harbor_id
        fi
        
        return 1
    fi

    available_line_number=0
    if [ $last_nonblank_number -lt 254 ]; then
        available_line_number=`expr $last_nonblank_number + 1`
    else
        available_line_number=$first_blank_number
    fi

    sed -i "${available_line_number}s/.*/${process_name}/g" ${LOCK_FILE}
    harbor_id=`expr $available_line_number + 1`
    framework_log "allocate harbor id $harbor_id to $process_name"
    echo $harbor_id
    return 0
}

{
    flock -x 7
    allocate_harbor_id
} 7<>$LOCK_FILE