#!/bin/sh
# A stand-in for droidlock in the tests of a project's scripts. Put it on PATH as `droidlock`.
#
# It appends each call to the file that DROIDLOCK_STUB_LOG names, one line for each call. acquire
# prints a grant of the resource stub-0 with the lease stub-lease and the serial stub-serial, or
# keeps the lease that --lease names, or exits with DROIDLOCK_STUB_STATUS, for example 4 for a
# machine whose devices are all in use. The grant has PREVIOUS=other and STARTED=false, or the
# values of DROIDLOCK_STUB_PREVIOUS and DROIDLOCK_STUB_STARTED. run runs the command after -- as
# droidlock run --lease runs it for a device: with the serial stub-serial in DROIDLOCK_SERIAL,
# DROIDLOCK_SERIALS, and ANDROID_SERIAL, with the resource stub-0, or the one that --resource
# names, in DROIDLOCK_RESOURCE and DROIDLOCK_RESOURCES, with the lease stub-lease, or the one that
# --lease names, in DROIDLOCK_LEASE, also for --holding, and with each argument {serial},
# {resource}, {serials}, and {resources} replaced. Every other command does nothing.

if [ -n "${DROIDLOCK_STUB_LOG:-}" ]; then
    printf '%s\n' "$*" >>"$DROIDLOCK_STUB_LOG"
fi
case $1 in
    acquire)
        if [ -n "${DROIDLOCK_STUB_STATUS:-}" ]; then
            exit "$DROIDLOCK_STUB_STATUS"
        fi
        lease=stub-lease
        kept=false
        previous=${DROIDLOCK_STUB_PREVIOUS:-other}
        started=${DROIDLOCK_STUB_STARTED:-false}
        while [ "$#" -gt 0 ]; do
            if [ "$1" = --lease ]; then
                lease=$2
                kept=true
                previous=self
                started=false
            fi
            shift
        done
        printf 'RESOURCE=stub-0\nKIND=stub\nLEASE=%s\nSTATE=ready\nKEPT=%s\n' "$lease" "$kept"
        printf 'PREVIOUS=%s\nSTARTED=%s\n' "$previous" "$started"
        printf 'SERIAL=stub-serial\n'
        ;;
    run)
        shift
        unset DROIDLOCK_ACCOUNTS DROIDLOCK_HANDLE
        export DROIDLOCK_KIND=stub DROIDLOCK_SERIAL=stub-serial ANDROID_SERIAL=stub-serial
        export DROIDLOCK_SERIALS=stub-serial DROIDLOCK_RESOURCE=stub-0 DROIDLOCK_LEASE=stub-lease
        while [ "$#" -gt 0 ]; do
            case $1 in
                --resource) DROIDLOCK_RESOURCE=$2 ;;
                --lease) DROIDLOCK_LEASE=$2 ;;
                --)
                    shift
                    break
                    ;;
            esac
            shift
        done
        export DROIDLOCK_RESOURCES="$DROIDLOCK_RESOURCE"
        # Only a whole argument is replaced, as droidlock run does.
        for argument; do
            shift
            case $argument in
                '{serial}' | '{serials}') set -- "$@" stub-serial ;;
                '{resource}' | '{resources}') set -- "$@" "$DROIDLOCK_RESOURCE" ;;
                *) set -- "$@" "$argument" ;;
            esac
        done
        exec "$@"
        ;;
esac

