1#!/bin/bash
2set -euo pipefail
3
4function get_cid {
5    local max_cid
6    max_cid=$(/apex/com.android.virt/bin/vm list | awk 'BEGIN { FS="[:,]" } /cid/ { print $2; }' | sort -n | tail -1)
7
8    # return the value trimmed from whitespaces
9    echo "${max_cid}" | xargs
10}
11
12function wait_for_cid {
13    TIMES=${1:-20}
14    X=0
15    local init_cid
16    init_cid=$(get_cid)
17    while [ "$TIMES" -eq 0 ] || [ "$TIMES" -gt "$X" ]
18    do
19      local cid
20      cid=$(get_cid)
21      echo "wait_for_cid: retry $(( X++ )) / $TIMES : init_cid=$init_cid cid=$cid";
22      if [ "$cid" -gt "$init_cid" ]
23      then
24        break
25      else
26        sleep 2
27      fi
28    done
29    setprop trusty.test_vm.vm_cid "$cid"
30}
31
32# This script is expected to be started before the trusty_test_vm is started
33# wait_for_cid gets the max cid and wait for it to be updated as an indication
34# that the trusty_test_vm has properly started.
35# wait_for_cid polls for the CID change at 2 seconds intervals
36# the input argument is the max number of retries (20 by default)
37wait_for_cid "$@"
38
39echo trusty.test_vm.vm_cid="$(getprop trusty.test_vm.vm_cid)"
40