#!/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.
#
# This script prepares the new agent and install it on the vm
#

set -euo pipefail

usage() (
    echo "Usage: agent_update-self_update_test_setup -p|--package <path> -v|--version <version>  -u|--update_to_latest_version <y|n>"
    exit 1
)

while [[ $# -gt 0 ]]; do
    case $1 in
        -p|--package)
            shift
            if [ "$#" -lt 1 ]; then
                usage
            fi
            package=$1
            shift
            ;;
        -v|--version)
            shift
            if [ "$#" -lt 1 ]; then
                usage
            fi
            version=$1
            shift
            ;;
        -u|--update_to_latest_version)
            shift
            if [ "$#" -lt 1 ]; then
                usage
            fi
            update_to_latest_version=$1
            shift
            ;;
        *)
            usage
    esac
done
if [ "$#" -ne 0 ] || [ -z ${package+x} ] || [ -z ${version+x} ]; then
    usage
fi

echo "updating the related to self-update flags"
update-waagent-conf AutoUpdate.UpdateToLatestVersion=$update_to_latest_version AutoUpdate.GAFamily=Test Debug.EnableGAVersioning=n Debug.SelfUpdateHotfixFrequency=120 Debug.SelfUpdateRegularFrequency=120 Autoupdate.Frequency=120
agent-service stop
mv /var/log/waagent.log /var/log/waagent.$(date --iso-8601=seconds).log

# Some distros may pre-install higher version than custom version that test installs, so we need to lower the version to install custom version
agent_update-modify_agent_version 2.2.53

echo "Cleaning up the existing agents"
rm -rf /var/lib/waagent/WALinuxAgent-*

echo "Installing $package as version $version..."
unzip.py $package /var/lib/waagent/WALinuxAgent-$version
agent-service restart

