1#!/bin/bash
2
3#TODO(b/35570956): Do with Soong instead.
4
5#Note: see do_makefiles_update below.
6
7function package_root_to_package() {
8  echo $1 | cut -f1 -d:
9}
10
11function package_root_to_root() {
12  echo $1 | cut -f2 -d:
13}
14
15##
16# Makes sure the appropriate directories are visible.
17# Usage: check_dirs root_or_cwd [package:root ...]
18function check_dirs() {
19  local root_or_cwd=$1
20  shift 1
21
22  for package_root in "$@"; do
23      dir=$(package_root_to_root $package_root)
24      if [ ! -d $root_or_cwd$dir ] ; then
25        echo "Where is $dir?";
26        return 1;
27      fi
28  done
29}
30
31##
32# Gets all packages in a directory.
33# Usage: get_packages package root
34function get_packages() {
35  local current_dir=$1
36  local current_package=$2
37  pushd $current_dir > /dev/null;
38  find . -type f -name \*.hal -exec dirname {} \; | sort -u | \
39    cut -c3- | \
40    awk -F'/' \
41    '{printf("'$current_package'"); for(i=1;i<NF;i++){printf(".%s", $i);}; printf("@%s\n", $NF);}';
42  popd > /dev/null;
43}
44
45##
46# Package roots to arguments.
47# Usage: get_root_arguments [package:root ...]
48function get_root_arguments() {
49  for package_root in "$@"; do
50      echo "-r $package_root"
51  done
52}
53
54##
55# Returns directory path for a package
56# Usage: get_package_dir package_root_dir package_prefix package
57function get_package_dir() {
58  local package_dir=`echo $3 | cut -f1 -d@ | sed "s/$2\.//" | sed "s/\./\//g"`
59  local package_version=`echo $3 | cut -f2 -d@`
60  echo $1/$package_dir/$package_version
61}
62
63##
64# Helps manage the package root of a HAL directory.
65# Should be called from the android root directory.
66#
67# Usage: do_makefiles_update [-O owner-name] [package:root ...]
68# Where the first package root is the current one.
69#
70function do_makefiles_update() {
71  local owner=
72  if [[ "$1" = "-O" ]]; then
73      owner="$2"
74      shift 2
75  fi
76
77  local root_or_cwd=${ANDROID_BUILD_TOP%%/}${ANDROID_BUILD_TOP:+/}
78
79  local current_package=$(package_root_to_package $1)
80  local current_dir=$root_or_cwd$(package_root_to_root $1)
81
82  echo "Updating makefiles for $current_package in $current_dir."
83
84  check_dirs "$root_or_cwd" $@ || return 1
85
86  local packages=$(get_packages $current_dir $current_package) || return 1
87  local root_arguments=$(get_root_arguments $@) || return 1
88
89  for p in $packages; do
90    echo "Updating $p";
91    hidl-gen -O "$owner" -Landroidbp $root_arguments $p;
92    rc=$?; if [[ $rc != 0 ]]; then return $rc; fi
93  done
94}
95