#!/bin/bash

config_file="/usr/local/omc/etc/restconf.yaml"
temp_file="/tmp/temp.yaml"

declare -A insert_lines=(
    [156]="    dataCoding: 0"
    [157]="    serviceNumber: \"OMC\""
)

declare -A update_lines=(
    ["deadLine: 10"]="deadLine: 600"
)

# check if exist file
if [[ ! -f $config_file ]]; then
    echo "NOT FOUND config file: $config_file"
    exit 1
fi

insert_if_missing() {
    local line_number="$1"
    local line_content="$2"
    local current_content=$(sed -n "${line_number}p" "$config_file")

    if [[ "$current_content" != "$line_content" ]]; then
        # insert line to config file
        echo -n "Inserting '$line_content' into line ${line_number} ... "
        awk -v n="$line_number" -v line="$line_content" 'NR==n {print line} {print}' "$config_file" >"$temp_file" && mv "$temp_file" "$config_file"
        if [ $? = 0 ]; then
            echo "done"
        fi
    else
        echo "Exist '$line_content' at line ${line_number}"
    fi
}

# function：update line content
update_lines_content() {
    local old_line="$1"
    local new_line="$2"
    echo -n "Updating '$old_line' to line '$new_line' ..."
    sed -i "s/$old_line/$new_line/" "$config_file"
    if [ $? = 0 ]; then
        echo "done"
    fi
}

#line_numbers=(156 157)
line_numbers=$(for key in "${!insert_lines[@]}"; do echo "$key"; done | sort -n)

# insert process
#for line_number in "${line_numbers[@]}"; do
#for line_number in "${!insert_lines[@]}"; do
for line_number in $line_numbers; do
    insert_if_missing "$line_number" "${insert_lines[$line_number]}"
done

# update process
for old_line in "${!update_lines[@]}"; do
    update_lines_content "$old_line" "${update_lines[$old_line]}"
done
