#!/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.
#
set -euo pipefail

usage() (
    echo "Usage: install-agent -p|--package <path> -v|--version <version>"
    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
            ;;
        *)
            usage
    esac
done
if [ "$#" -ne 0 ] || [ -z ${package+x} ] || [ -z ${version+x} ]; then
    usage
fi

#
# Find the command to manage services
#
if command -v systemctl &> /dev/null; then
  service-status() { systemctl --no-pager -l status $1; }
  service-stop()   { systemctl stop $1; }
  service-start()  { systemctl start $1; }
else
  service-status() { service $1 status; }
  service-stop()   { service $1 stop; }
  service-start()  { service $1 start; }
fi

#
# Find the service name (walinuxagent in Ubuntu and waagent elsewhere)
#
if service-status walinuxagent > /dev/null 2>&1;then
    service_name="walinuxagent"
else
    service_name="waagent"
fi
echo "Service name: $service_name"

#
# Output the initial version of the agent
#
python=$(get-agent-python)
waagent=$(get-agent-bin-path)
echo "Agent's path: $waagent"
$python "$waagent" --version
printf "\n"

#
# Install the package
#
echo "Installing $package as version $version..."
unzip.py "$package" "/var/lib/waagent/WALinuxAgent-$version"

# Ensure that AutoUpdate is enabled. some distros, e.g. Flatcar, don't have a waagent.conf
# but AutoUpdate defaults to True so there is no need to do anything in that case.
if [[ -e /etc/waagent.conf ]]; then
  sed -i 's/AutoUpdate.Enabled=n/AutoUpdate.Enabled=y/g' /etc/waagent.conf
fi

#
# Restart the service
#
echo "Restarting service..."
service-stop $service_name

# Rename the previous log to ensure the new log starts with the agent we just installed
mv /var/log/waagent.log /var/log/waagent."$(date --iso-8601=seconds)".log

service-start $service_name

#
# Verify that the new agent is running and output its status.
# Note that the extension handler may take some time to start so give 1 minute.
#
echo "Verifying agent installation..."

check-version() {
  for i in {0..5}
  do
    if $python "$waagent" --version | grep -E "Goal state agent:\s+$version" > /dev/null; then
      return 0
    fi
    sleep 10
  done

  return 1
}

if check-version "$version"; then
  printf "\nThe agent was installed successfully\n"
  exit_code=0
else
  printf "\nFailed to install agent.\n"
  exit_code=1
fi

$python "$waagent" --version
printf "\n"
service-status $service_name

exit $exit_code
