#!/usr/bin/env bash

# Microsoft Azure Linux Agent
#
# Copyright 2018 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#
# Updates waagent.conf with the specified setting and value(allows multiple) and restarts the Agent.
#

set -euo pipefail

if [[ $# -lt 1 ]]; then
    echo "Usage: update-waagent-conf [<setting=value>]"
    exit 1
fi

PYTHON=$(get-agent-python)
waagent_conf=$($PYTHON -c 'from azurelinuxagent.common.osutil import get_osutil; print(get_osutil().agent_conf_file_path)')
for setting_value in "$@"; do
    IFS='=' read -r -a setting_value_array <<< "$setting_value"
    name=${setting_value_array[0]}
    value=${setting_value_array[1]}

    if [[ -z "$name" || -z "$value" ]]; then
        echo "Invalid setting=value: $setting_value"
        exit 1
    fi
    echo "Setting $name=$value in $waagent_conf"
    sed -i -E "/^$name=/d" "$waagent_conf"
    sed -i -E "\$a $name=$value" "$waagent_conf"
    updated=$(grep "$name" "$waagent_conf")
    echo "Updated value: $updated"
done
agent-service restart