#/bin/sh
#
# Create a database of possible controling terminals
#
# Outputs a structure definition holding the three fields
#
#	Major Number
#	Minor Number
#	TTY name
#
# This is used to search for tty names, given major and minor numbers
#
# The structure is populated with data as follows
#
#  Output the structure definition

#  list /dev
#  Filter out just character special files
#  filter out files with tty or pts in them (This could be more robust)
#  Extract just the major, minor numbers and the name 
#  Sort them in numeric order Major # - primary key, Minor # - secondary key 
#  Re-order the fields so we can extract duplicate entries(keep first)
#  finally formatting as a table entry
#  Lastly finish up structure declaration.

FILE="ttydb.h"

echo "struct _ttydb {" >$FILE
echo "   int  major_no;"  >>$FILE
echo "   int  minor_no;"  >>$FILE
echo "   char *name;"  >>$FILE
echo "};"  >>$FILE
echo  >>$FILE

echo "struct _ttydb Ttydb[] = {"  >>$FILE

TF=/tmp/mkttydb.$$

/bin/ls -l /devices/pseudo | tail +2 | sed 's/\,/ /' | awk '{ print $5, $6, $10 }'  > $TF

# Here I create entrys for the "master" side of streams psuedo-tty, these
# do not exist in the dev tree, the proc system reports a device 23(major #)
# whose minor number matches the slave minor number. So I create a ptm# in
# an attempt to be more useful than the raw major/minor numbers. And they
# can do a "man ptm" to hopefully figure it out. This also assumes you
# are not building kernels and/or changing the major number of these devices.

for i in 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 
do
	echo "23 $i xxx:ptm$i" >> $TF
done

# Note that ptmajor hides the definition of ptm0, from what I understand
# it's only used during contruction of the stream pair so it's not likely
# to be seen and also not ptm0,pts0 pair gets created.

( grep console $TF; grep tty $TF ; grep pty $TF ; grep pts $TF ; grep ptm $TF) | sort -n -k 1,1 -k 2,2 | awk '{ printf "%s:%s:%s\n", $1, $2, $3 }' | awk -F: '
							\
$4  ~ /^[0-9]+$/    { printf "{ %s, %s, \"pts%s\" }, \n",  $1, $2, $4  }  \
$4 !~ /^[0-9]+$/    { printf "{ %s, %s, \"%s\" }, \n",     $1, $2, $4  }  ' | uniq >> $FILE

# You may need to add more of these, it's 2 am and I don't feel much
# like awking anymore!!!

echo "{ 100, 1, \"vt01\" },"  >>$FILE
echo "{ 100, 2, \"vt02\" },"  >>$FILE
echo "{ 100, 3, \"vt03\" },"  >>$FILE
echo "{ 100, 4, \"vt04\" },"  >>$FILE
echo "{ 100, 5, \"vt05\" },"  >>$FILE
echo "{ 100, 6, \"vt06\" },"  >>$FILE
echo "{ 100, 7, \"vt07\" },"  >>$FILE
echo "{ 100, 8, \"vt08\" },"  >>$FILE
echo "{ 100, 9, \"vt09\" },"  >>$FILE
echo "{ 100, 10, \"vt10\" },"  >>$FILE
echo "{ 100, 11, \"vt11\" },"  >>$FILE
echo "{ 100, 12, \"vt12\" },"  >>$FILE

echo "{ -1, -1, \"\" },"  >>$FILE

echo "};"  >>$FILE


rm $TF
