#!/bin/sh

set -eu

if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <udev kernel name>" >&2
    exit 2
fi

ALIASES=/proc/device-tree/aliases

case "$1" in
    ttyAMA0)
        UART=uart0
        ;;
    ttyAMA1)
        if [ -e /dev/ttyAMA0 ]; then
            echo "ttyAMA0 exists; ttyAMA1 is not built-in" >&2
            exit 1
        fi
        UART=uart0
        ;;
    ttyS0)
        UART=uart1
        ;;
    *)
        exit 1
        ;;
esac

if cmp -s "$ALIASES"/"$UART" "$ALIASES"/serial0; then
    echo 0
elif cmp -s "$ALIASES"/"$UART" "$ALIASES"/serial1; then
    echo 1
else
    echo "UART device is not serial0 or serial1" >&2
    exit 1
fi
