#!/bin/bash
# Copyright 2020 Google Inc. All rights reserved.
#
# 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.
#
#
# Given a project, a GCE instance ID, a zone, and an Ops agent policy ID. This
# script automatically collects necessary information to help with diagnosing
# issues with the policy:
#
# * The OS Config agent version
# * The underlying OS policy assignment
# * The OS policy assignments that are applicable to this GCE instance
# * The GCE VM instance
#
# Sample usage:
#    bash diagnose_policies.sh --project-id=PROJECT_ID --zone=ZONE --gce-instance-id=GCE_INSTANCE_ID --policy-id=POLICY_ID > diagnose.txt
#
# Ignore the return code of command substitution in variables.
# shellcheck disable=SC2155

set -e

show_usage(){
  echo "Usage: bash diagnose_policies.sh --project-id=PROJECT_ID --zone=ZONE --gce-instance-id=GCE_INSTANCE_ID --policy-id=POLICY_ID"
}

if [[ $# -le 2 ]]; then
  show_usage 0
  exit 1
fi

while getopts -- '-:' OPTCHAR; do
  case "${OPTCHAR}" in
    -)
      case "${OPTARG}" in
        project-id=*) PROJECT_ID="${OPTARG#*=}" ;;
        zone=*) ZONE="${OPTARG#*=}" ;;
        gce-instance-id=*) GCE_INSTANCE_ID="${OPTARG#*=}" ;;
        policy-id=*) POLICY_ID="${OPTARG#*=}" ;;
        *) fail "Unknown option '${OPTARG}'." ;;
      esac
  esac
done

echo "Step 1: Get the OS Config agent version on the problematic GCE instances."
gcloud compute instances os-inventory describe \
    "$GCE_INSTANCE_ID" \
    --project "$PROJECT_ID" \
    --zone "$ZONE" \
    | grep OSConfigAgentVersion

echo "Step 2: Get the underlying OS policy assignment."
gcloud compute os-config os-policy-assignments describe \
    "$POLICY_ID" \
    --project "$PROJECT_ID" \
    --location "$ZONE"

echo "Step 3: Look up the OS policy assignments that are applicable to this specific GCE instance."
gcloud compute os-config os-policy-assignment-reports list \
    --project "$PROJECT_ID" \
    --location="$ZONE" \
    --instance="$GCE_INSTANCE_ID"

echo "Step 4: Describe the GCE VM Instance"
gcloud compute instances describe \
    "$GCE_INSTANCE_ID" \
    --project "$PROJECT_ID" \
    --zone "$ZONE"
