#!/bin/bash
# Copyright 2020 Google LLC
#
# 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
#
#     https://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.

# Deletes the least recent N versions deployed to App Engine, where those
# versions are not serving any traffic.
#
# This does not specify `--project` as it's part of the environment.
# However, it forwards all command-line arguments to gcloud for both listing
# and deletion, useful for test: run with `./cleanup.sh --project foo`.

set -eu

KEEP=100  # keep 100, App Engine's limit is between 200-1000
COUNT=8   # only delete <X> per time, gcloud is slow
SERVICE=default

# The grep command below matches versions like:
#   20201207t043317
# (8 digits, "t", 6 digits).
# ... as these are autogenerated by gcloud. We use [[:digit:]] instead of \d:
# the short version is supported on macOS but not on Linux.

# Grab the project ID for logging (we pass $@ to all calls).
PROJECT_ID=$(gcloud config list --format 'value(core.project)' $@ 2>/dev/null)
if [ "${PROJECT_ID}" == "" ]; then
  echo "No project available. Specify in environment or via \"--project <x>\""
  exit 1
fi
echo "Looking up old versions for \"${PROJECT_ID}\"..."

while true; do
  VERSIONS=$(gcloud app versions list \
      --service $SERVICE \
      --filter 'traffic_split = 0' \
      --sort-by '~last_deployed_time' \
      --format 'value(version.id)' \
      $@ \
          | grep -E "^[[:digit:]]{8}t[[:digit:]]{6}$" \
          | tail -n +$KEEP | tail -n $COUNT | paste -sd " " -)

  if [ ${#VERSIONS} -eq 0 ]; then
    echo "Done, no versions to delete."
    exit 0
  fi
  echo "Deleting: ${VERSIONS}"
  gcloud app versions delete --service $SERVICE $VERSIONS -q $@
done
