#!/bin/sh

. config/path

KCONFIG=build/config/Kconfig.machine

cat > $KCONFIG <<EOF
############################################
# This file is autogenerated, do not edit! #
############################################

choice
  prompt "Target machine"
  help
    Target board or machine we want to compile for

EOF

for i in config/platforms/*; do
  arch=`basename $i`
  for j in config/platforms/$arch/*; do
    [ -d "$j" ] || continue
    platform=`basename $j`
    for k in config/platforms/$arch/$platform/machines/*; do
      machine=`basename $k`
      [ -r config/platforms/$arch/$platform/machines/$machine/meta ] || continue

       # clear MACHINE_* variables
       for var in `set | grep -E '^MACHINE_.*$' | cut -f1 -d=`; do
         unset $var
       done

      . config/platforms/$arch/$platform/machines/$machine/meta
      [ -z "$MACHINE_DESC" ] && MACHINE_DESC="$MACHINE_NAME"
      cat >> $KCONFIG <<EOF
config TARGET_MACHINE_${arch}_${platform}_${machine}
  bool "$MACHINE_DESC"
  depends on TARGET_PLATFORM_${arch}_${platform}
EOF
      [ -n "$MACHINE_CPU" ] && \
        echo "  select TARGET_CPU_${MACHINE_CPU}" >> $KCONFIG
      for pkg in $MACHINE_DEPENDS; do
        echo "  select PKG_$pkg" >> $KCONFIG
      done
      for flag in $MACHINE_USE; do
        val=`valueof MACHINE_DEPENDS_$flag`
        for pkg in $val; do
          echo "  select PKG_$pkg if USE_$flag" >> $KCONFIG
        done
      done
[ -n "$MACHINE_HELP" ] && cat >> $KCONFIG <<EOF
  help
    $MACHINE_HELP
EOF
    done
  done
done

cat >> $KCONFIG <<EOF

endchoice

config OPT_TARGET_MACHINE
  string
EOF

for i in config/platforms/*; do
  arch=`basename $i`
  for j in config/platforms/$arch/*/; do
    [ -d $j ] || continue
    platform=`basename $j`
    for k in config/platforms/$arch/$platform/machines/*; do
      machine=`basename $k`
      [ -r config/platforms/$arch/$platform/machines/$machine/meta ] || continue
      echo "  default \"$machine\" if TARGET_MACHINE_${arch}_${platform}_${machine}" >> $KCONFIG
    done
  done
done

