1#!/bin/bash
2
3# This is a script to release the Debian image built by Kokoro to Lorry.
4
5set -e
6
7show_help() {
8	echo "Usage: $0 [OPTION]..."
9	echo "Fetches a debian image from Placer and releases it to /android/ferrochrome/ARCH/TAG"
10	echo "Options:"
11	echo "-h            Print usage and this help message and exit."
12	echo "-a ARCH       Architecture of the image. Defaults to all supported architectures."
13	echo "-b BUILD_ID   Build ID to fetch. If omitted, latest build ID is selected."
14	echo "-t TAG        Tag name to attach to the release. Defaults to BUILD_ID."
15}
16
17parse_opt() {
18	while getopts "ha:b:t:" option; do
19		case ${option} in
20			h)
21				show_help
22				exit;;
23			a)
24				if [[ "$OPTARG" != "aarch64" && "$OPTARG" != "x86_64" ]]; then
25					echo "Invalid architecture: $OPTARG"
26					exit
27				fi
28				arch="$OPTARG"
29				;;
30			b)
31				build_id="$OPTARG"
32				;;
33			t)
34				tag="$OPTARG"
35				;;
36			*)
37				echo "Invalid option: $OPTARG"
38				exit
39				;;
40		esac
41	done
42
43	if [ "${build_id}" != "latest" ]; then
44		echo "Build ID is ambiguous when architecture is not set"
45		exit
46	fi
47}
48
49arch=all
50build_id=latest
51tag=
52placer_url="/placer/test/home/kokoro-dedicated-qa/build_artifacts/qa/android-ferrochrome"
53image_filename="images.tar.gz"
54
55get_build_id() {
56	local arch=$1
57	local build_id=$2
58	if [ "${build_id}" == "latest" ]; then
59		local pattern=${placer_url}/${arch}/continuous
60		build_id=$(basename $(fileutil ls ${pattern} | sort -V | tail -1))
61	fi
62	echo ${build_id}
63}
64
65get_image_path() {
66	local arch=$1
67	local build_id=$2
68	local pattern=${placer_url}/${arch}/continuous/${build_id}/*/${image_filename}
69	image=$(fileutil ls ${pattern} | tail -1)
70	if [ $? -ne 0 ]; then
71		echo "Cannot find image"
72		exit
73	fi
74	echo ${image}
75}
76
77do_release() {
78	local arch=$1
79	local build_id=$2
80
81	build_id=$(get_build_id ${arch} ${build_id})
82	echo "Using build ID ${build_id} for ${arch}"
83	local image=$(get_image_path ${arch} ${build_id})
84
85	local tag=${tag:-${build_id}}
86	local serving_url=/android/ferrochrome/${tag}/${arch}/${image_filename}
87	echo "Releasing ${image} to ${serving_url}"
88
89	local request='payload : { url_path: '"\"${serving_url}\""' source_path : '"\"${image}\""' }'
90	local id=$(stubby call blade:download-lorry-api LorryService.CreatePayloads "${request}" | cut -d\  -f2)
91	echo "Done. Visit https://lorry.corp.google.com/view/${id} to get an approval for the release."
92}
93
94parse_opt "$@"
95
96if [ "${arch}" == "all" ]; then
97	do_release aarch64 ${build_id}
98	do_release x86_64 ${build_id}
99else
100	do_release ${arch} ${build_id}
101fi
102