#!/usr/bin/env bash
# android_emu_rotate — rotate emulator screen or toggle rotation

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./adb_wsl.sh
source "$SCRIPT_DIR/adb_wsl.sh"

android_emu_rotate() {
    adb_pick_serial "$@" || exit 3
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    local arg="${1:-}"

    # Disable autorotate before any operation
    if [[ -n "$arg" ]]; then
        adb_s "$serial" shell settings put system accelerometer_rotation 0
    fi

    case "$arg" in
        "")
            # Toggle via emu rotate command
            adb_s "$serial" emu rotate
            ;;
        portrait|0)
            adb_s "$serial" shell settings put system accelerometer_rotation 0
            adb_s "$serial" shell settings put system user_rotation 0
            ;;
        landscape|90)
            adb_s "$serial" shell settings put system accelerometer_rotation 0
            adb_s "$serial" shell settings put system user_rotation 1
            ;;
        180)
            adb_s "$serial" shell settings put system accelerometer_rotation 0
            adb_s "$serial" shell settings put system user_rotation 2
            ;;
        270)
            adb_s "$serial" shell settings put system accelerometer_rotation 0
            adb_s "$serial" shell settings put system user_rotation 3
            ;;
        *)
            echo "android_emu_rotate: unknown orientation '$arg'" >&2
            echo "Usage: android_emu_rotate [--serial <S>] [portrait|landscape|0|90|180|270]" >&2
            return 1
            ;;
    esac

    echo "rotated: ${arg:-toggle} on $serial"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    android_emu_rotate "$@"
fi
