#!/bin/sh
#
# $NetBSD: mkplists,v 1.2 2011/11/21 19:08:57 absd Exp $
#
# Author: Martti Kuparinen <martti@NetBSD.org>
#
# This is an ugly script to generate the required PLIST.* files.
#
# Usage:
#
#   bmake extract
#   sh files/mkplists
#

cd `pwd`/work/linux-*/include

echo "Creating temporary sets for each ARCH"
for i in asm-*
do
    [ ${i} = asm-generic ] && continue
    echo "==> ${i}"

    rm -rf /tmp/${i}
    tar cf - ${i} | tar xf - -C /tmp
    (cd asm-generic && tar cf - *) | tar xf - -C /tmp/${i}
done

echo "Getting list of all files per ARCH"
for i in asm-*
do
    [ ${i} = asm-generic ] && continue
    find /tmp/${i}/ -type f -or -type l | sed "s+/tmp/${i}/++" | sort \
        > /tmp/list-${i}
done

echo "Getting list of all files for all ARCHs"
cat /tmp/list-* | sort | uniq > /tmp/all

echo "Generating PLIST.* entries"
rm -f /tmp/PLIST.*
echo "@comment \$NetBSD\$" >> /tmp/PLIST.common
for i in asm-*
do
    [ ${i} = asm-generic ] && continue
    P=`echo ${i} | sed 's+.*-++'`
    echo "@comment \$NetBSD\$" >> /tmp/PLIST.${P}
done

for i in `cat /tmp/all`
do
    # Does this file exist in all directories?
    echo -n "==> ${i}: "

    IGNORED=
    for j in /tmp/list-*
    do
        X=`grep "^${i}$" ${j}`
        if [ -z "${X}" ]; then
            # The searched file was not found in this ARCH
            IGNORED="${IGNORED} `basename ${j}` "
        fi
    done

    if [ -z "${IGNORED}" ]; then
        # This file is found in all ARCHs
        echo "PLIST.common"
        echo "include/asm/${i}" >> /tmp/PLIST.common
    else
        # Generate the ARCH specific PLISTs
        for k in asm-*
        do
            [ ${k} = asm-generic ] && continue

            SKIP=`echo "${IGNORED}" | grep " list-${k} "`
            [ ! -z "${SKIP}" ] && continue

            P=`echo ${k} | sed 's+.*-++'`
            echo -n "PLIST.${P} "
            echo "include/asm/${i}" >> /tmp/PLIST.${P}
        done
        echo ""
    fi
done

echo "Adding include/linux files"
find linux -type f -or -type l | sed 's+^+include/+' | sort >> /tmp/PLIST.common

echo "Sorting everything"
for i in /tmp/PLIST.*
do
    sort ${i} > ${i}.new
    /bin/mv ${i}.new ${i}
done

echo "Removing // and trailing / from PLIST files"
for i in /tmp/PLIST.*
do
    sed -e 's+//+/+g' -e 's+/$++' < ${i} > ${i}.new
    /bin/mv ${i}.new ${i}
done

echo "Removing the temporary files."
rm -rf /tmp/list-asm-* /tmp/asm-* /tmp/all

echo "All done. The new PLIST files are now in /tmp."
