#!/bin/sh

# Script which detect automaticaly the alsa-conf file to put
# in place in function of board on which the script are executed.
#
# This script are use with systemd-generators
# see man for more information or
# https://www.freedesktop.org/software/systemd/man/systemd.generator.html
#
# How to debug:
# mkdir /tmp/normal-dir /tmp/early-dir /tmp/late-dir
# SYSTEMD_LOG_LEVEL=debug /lib/systemd/system-generators/system-generator-alsa-conf \
#        /tmp/normal-dir /tmp/early-dir /tmp/late-dir
# find /tmp/normal-dir /tmp/early-dir /tmp/late-dir
#
#
function debug_print() {
    if `echo $SYSTEMD_LOG_LEVEL |grep -q debug` ;
    then
        echo "[DEBUG] $@"
    fi
}

#
# Main
#
if [ ! -d /proc/device-tree/ ];
then
    debug_print "Proc Device tree are not available, Could not detect on which board we are"
    exit 1
fi
if [ -e /etc/asound.conf ];
then
    LINE=`cat /etc/asound.conf | wc -l`
    if [ $LINE -lt 3 ];
    then
        # dummy asound.conf file contains only one comment
        debug_print "remove previous dummy asound.conf file"
        rm /etc/asound.conf
    else
        debug_print "asound.conf file already configured"
        exit 0
    fi
fi
# get the name file available for alsa-conf
ALSA_CONF_FILES=`ls -1 /etc/asound-*`

for f in $ALSA_CONF_FILES;
do
    #extract name of board
    board=`echo $f | sed -e "s|/etc/asound-\(.*\).conf|\1|"`
    debug_print "board=$board"
    #search on device tree compatible entry if the board are present
    if `grep -q $board /proc/device-tree/compatible` ;
    then
        # device tree compatible entry match with board name
        debug_print "use $f for asound.conf"
        cp $f /etc/asound.conf
        break;
    fi
done
exit 0
