1# Copyright (C) 2018 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15script_name="${0##*/}"
16script_dir="${0%/*}"
17
18# Exit with 1 with printing a given message on stderr.
19function die() {
20    echo "$script_name: ERROR: $@" 1>&2
21    exit 1
22}
23
24# Print a given message on stderr.
25function warn() {
26    echo "$script_name: WARN: $@" 1>&2
27}
28
29# Print a given message on stderr.
30function info() {
31    echo "$script_name: $@" 1>&2
32}
33
34# Wrapper around "adb".
35function do_adb() {
36    adb $ADB_OPTIONS "$@"
37}
38
39# Return the timestamp of the most recent log line, which can be later used with logcat -t or -T.
40function get_last_logcat_timestamp() {
41    # Output will be like this. Extract the timestamp.
42    #--------- beginning of main
43    #06-14 00:04:43.909  3993  3993 E QtiImsExtUtils: isCarrierConfigEnabled bundle is null
44
45    do_adb logcat -t 1 | awk '(match($0, "^[0-9]")){print $1 " " $2}'
46}
47
48# If $1 is a number, just print it. Otherwise use adb shell pidof to try to resolve it into a pid.
49function resolve_pid() {
50    local name="$1"
51
52    if [[ -z "$name" ]] ;then
53        return 1
54    fi
55
56    if [[ "$name" =~ ^[0-9]+$ ]] ; then
57        echo "$name"
58        return 0
59    fi
60    local pid="$(do_adb shell pidof "$name")"
61    if [[ -z "$pid" ]] ; then
62        die "unknown process: $name"
63    fi
64    echo "$pid"
65}
66
67# Find available local port. Optionally take the starting port from $1.
68function find_open_port() {
69    local port="${1:-10000}" # Take the start port from $1 with 10000 as the default.
70
71    while true; do
72        if netstat -an | grep -qw "$port"; then
73            port=$(( $port + 1 ))
74            continue
75        fi
76        break # Found
77    done
78
79    echo "$port"
80}
81
82# Create a temp file name with a timestamp.
83function make_temp_file() {
84    local suffix="$1"
85    local dir="${TMPDIR:-${TEMP:-/tmp}}"
86
87    while true; do
88        local file="$dir/temp-$(date '+%Y%m%d-%H%M%S')-$$$suffix"
89        if ! [[ -e "$file" ]] ; then
90            touch "$file"   # Note it's a bit racy..
91            echo "$file"
92            return 0
93        fi
94        sleep 0.5 # Ugh.
95    done
96}