#!/bin/bash

# usage: ./scripts/keyboard-scraper.sh
# setup enough of a chroot to run keyboard-configuration.config
# and scrape it for keyboard recommendations

set -eu

outfile=kbds/keyboard-configuration.yaml
langs=$(cat languagelist | cut -d: -f2)

tmpdir=$(mktemp -d -p $(pwd))
trap "rm -fr $tmpdir" EXIT

if [ ! -f keyboard-configuration.config ] ; then
    wget https://salsa.debian.org/installer-team/console-setup/-/raw/master/debian/keyboard-configuration.config
fi

# setup prerequisites for the config script
mkdir -p $tmpdir/bin
cp /usr/bin/busybox $tmpdir/bin/sh
ln $tmpdir/bin/sh $tmpdir/bin/sed
ln $tmpdir/bin/sh $tmpdir/bin/grep

mkdir -p $tmpdir/usr/share/debconf
touch $tmpdir/usr/share/debconf/confmodule

mkdir -p $tmpdir/dev
sudo mknod -m 666 $tmpdir/dev/null c 1 3

cp keyboard-configuration.config $tmpdir

# more prerequisites, and save db_set output for later consumption
cat > $tmpdir/stage2 <<EOF
all_kbdnames() { :; }
db_capb() { :; }
db_get() { :; }
keyboard_present() { false; }

dpkg()
{
    echo "$(dpkg --print-architecture)"
}

db_set()
{
    echo "\$1" "\$2" >> /db_set.\$LC_CTYPE
}

# LC_CTYPE is used by the config script to decide which locale we're providing
# a keyboard suggestion for.
LC_CTYPE="\$1"
export LC_CTYPE
. /keyboard-configuration.config
EOF
chmod 755 $tmpdir/stage2

cat > $outfile <<EOF
# File generated by $0, please do not edit manually
# Based on output from keyboard-configuration.config
EOF

for locale in $langs ; do
    echo "$locale"
    sudo chroot $tmpdir /bin/sh /stage2 "$locale"
    # transform interesting db_set values into a simplistic yaml format
    echo "$locale:" >> $outfile
    awk '
        /layoutcode/ {print "  layout: " "\""$2"\""}
        /variantcode/ {print "  variant: " "\""$2"\""}
    ' < $tmpdir/db_set.$locale >> $outfile
done

echo "output to $outfile"
