#!/bin/sh
set -e

assert_eq() {
    if [ "$1" != "$2" ]; then
        echo "FAIL: '$1' not equal to '$2'" >&2
        exit 1
    fi
}

assert_in() {
    if ! echo "$2" | grep -q "$1"; then
        echo "FAIL: '$1' not found in:" >&2
        echo "$2" >&2
        echo "--------" >&2
        exit 1
    fi
}

# list-modems should show phonesim modem
OUT=`/usr/share/ofono/scripts/list-modems`
assert_in "/phonesim" "$OUT"
assert_in "Powered = 1" "$OUT"
assert_in "org.ofono.VoiceCallManager" "$OUT"

# verify the D-BUS address file
assert_eq "`stat -c '%U' /run/lock/ofono-phonesim-dbus.address 2>&1`" "nobody"

# verify pid and user of phonesim process
assert_eq "`stat -c '%U' /run/lock/ofono-phonesim-dbus.pid 2>&1`" "nobody"
OUT=`ps U nobody`
assert_in "ofono-phonesim" "$OUT"

# stopping the job should go back to running normal ofono
stop ofono-phonesim
assert_in 'start/running' "`status ofono`"

# ... and not have a phonesim modem
OUT=`/usr/share/ofono/scripts/list-modems`
if echo "$OUT" | grep -q "/phonesim"; then
    echo "ERROR: /phonesim modem still present after stopping ofono-phonesim script!" >&2
    echo "$OUT" >&2
    exit 1
fi

# restart phonesim job again
start ofono-phonesim
sleep 2
assert_in 'stop/waiting' "`status ofono`"

# should be back to emulated
assert_in "/phonesim" "`/usr/share/ofono/scripts/list-modems`"
