#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2024-present JELOS (https://github.com/JustEnoughLinuxOS)

. /etc/profile

EXTLCONF=/flash/extlinux/extlinux.conf
EXTLCONFBAK=${EXTLCONF}.orig

case "$1" in
  "")
    echo $(cat /sys/firmware/devicetree/base/archr,device_switch/this | tr -d '\0')
    ;;
  "--options")
    echo $(ls /sys/firmware/devicetree/base/archr,device_switch/ | grep -Ev '^(name|this)$')
    ;;
  *)
    DTB=$(cat /sys/firmware/devicetree/base/archr,device_switch/$1 | tr -d '\0').dtb
    [[ $? -eq 0 ]] || { echo "Cannot resolve dtb name for $1" >&2; exit 2; }
    [ -f "/flash/${DTB}" ] || { echo "dtb not found: /flash/${DTB}"; exit 3; }

    mount -o remount,rw /flash

    [ -f ${EXTLCONFBAK} ] || cp ${EXTLCONF} ${EXTLCONFBAK}
    grep -q '^ *FDT ' ${EXTLCONF} || sed -i 's|^\(.* FDTDIR .*$\)|\1\n  FDT todo.dtb|' ${EXTLCONF}
    sed -i "s|^ *FDT .*$|  FDT /${DTB}|" ${EXTLCONF}

    echo $1 > /flash/device.name
    rm -r /storage/remappings/*

    sync
    mount -o remount,ro /flash
    ;;
esac

