#!/bin/bash

# Copyright (C) 2024 The Android Open Source Project
#
# 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
#
#      http://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.

# adb install a module's apk, as cached in module-info.json. If any build change
# is made, and it should be reflected in the output, you should run 'refreshmod' first.
# Usage: installmod [adb install arguments] <module>
# For example: installmod -r Dialer -> adb install -r /path/to/Dialer.apk

if [[ $# -eq 0 ]]; then
    echo "usage: installmod [adb install arguments] <module>" >&2
    echo "" >&2
    echo "Only flags to be passed after the \"install\" in adb install are supported," >&2
    echo "with the exception of -s. If -s is passed it will be placed before the \"install\"." >&2
    echo "-s must be the first flag passed if it exists." >&2
    return 1
fi

_path=$(outmod ${@:$#:1})
if [ $? -ne 0 ]; then
    return 1
fi

_path=$(echo "$_path" | grep -E \\.apk$ | head -n 1)
if [ -z "$_path" ]; then
    echo "Module '$1' does not produce a file ending with .apk (try 'refreshmod' if there have been build changes?)" >&2
    return 1
fi
serial_device=""
if [[ "$1" == "-s" ]]; then
    if [[ $# -le 2 ]]; then
        echo "-s requires an argument" >&2
        return 1
    fi
    serial_device="-s $2"
    shift 2
fi
length=$(( $# - 1 ))
echo adb $serial_device install ${@:1:$length} $_path
adb $serial_device install ${@:1:$length} $_path

