#!/bin/bash
# -*- Mode: sh; indent-tabs-mode: nil; tab-width: 4 -*-

# Our goal here is to get an Ubuntu Touch device into a testable unlocked state.
# This will include a reboot.

WAIT_COMMAND="sleep 20"

while getopts s:w: opt; do
        case $opt in
        s)
                export ANDROID_SERIAL=$OPTARG
                ;;
        w)
                WAIT_COMMAND=$OPTARG
                ;;
        esac
done

UNLOCK_SCRIPT='
import dbus, logging;
from unity8 import process_helpers as helpers;
logging.basicConfig(level=logging.INFO);
bus = dbus.SystemBus().get_object("com.canonical.powerd", "/com/canonical/powerd");
cookie = bus.requestSysState("unlock-device-hold", 1, dbus_interface="com.canonical.powerd");
helpers.restart_unity_with_testability();
bus.clearSysState(cookie, dbus_interface="com.canonical.powerd");
helpers.unlock_unity()
'

adb reboot
sleep 5
adb "wait-for-device"
eval "$WAIT_COMMAND"
UNLOCK_OUTPUT=$(adb shell "sudo -u phablet -i python3 -c '$UNLOCK_SCRIPT'" 2>&1)
if echo "$UNLOCK_OUTPUT" | grep 'Greeter unlocked' >/dev/null; then
    echo "I: Unlock passed"
    exit 0
else
    echo "I: Unlock failed, script output: '$UNLOCK_OUTPUT'"
    exit 1
fi
