#! /bin/bash

#*********************************************************************
#
# fai-class - determine all classes a host belongs to
#
# This script is part of FAI (Fully Automatic Installation)
# (c) 2002-2022 by Thomas Lange, lange@cs.uni-koeln.de
# Universitaet zu Koeln
#
#*********************************************************************
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# A copy of the GNU General Public License is available as
# `/usr/share/common-licences/GPL' in the Debian GNU/Linux distribution
# or on the World Wide Web at http://www.gnu.org/copyleft/gpl.html. You
# can also obtain it by writing to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#*********************************************************************

# import variables: $LOGDIR $verbose $debug
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
verbosemsg() {

    # a very nice subroutine
    # write message if the verbose flag is set
    [ X$verbose = X1 ] && echo "$*"
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
debugmsg() {

    # a very nice subroutine
    # write message if the debug flag is set
    [ "$debug" ] && echo "$0: $*"
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
addclass() {

    # append classes to a file
    while read line ; do
        case $line in
        \#*) ;; # strip comments
          *) debugmsg "Adding class $line"
             for class in $line ; do
                 echo $class >> $filename
             done
        esac
    done
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fc_check_status() {

    cmd=$1
    st=$2

    if [ $st -eq 0 ]; then
        res="OK."
    else
        res="FAILED with exit code $st."
        err=1
    fi
    # put result in the log file and write to stdout
    printf "%-20s $res\n" $cmd | tee -a $LOGDIR/status.log
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
usage() {

    ex=$1
    cat <<-EOF
        fai-class  Copyright (C) 2002-2022 Thomas Lange

        Usage: fai-class [OPTION] DIRECTORY CLASSFILE
        Define classes using files and scripts in DIRECTORY

        Executes scripts in DIRECTORY starting with two digits.
        The standard output of these scripts are names of classes which
        are written to CLASSFILE.
EOF
    exit $ex
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
testclass() {

    # test if some classes are define multiple times
    duplicate=$(sort $filename | uniq -dc)
    if [ -n "$duplicate" ]; then
        echo "$0: WARNING. Following classes are defined multiple times: $duplicate" >&2
        exit 2
    fi
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
setup() {

    # parse options, test and set some basic variables

    while getopts "dhvt:T" opt ; do
        case "$opt" in
        d) debug=1 ;;
        v) verbose=1 ;;
        h) usage 0 ;;
        T) ctest=1 ;;
        t) LOGDIR=$OPTARG; export LOGDIR ;;
        *) usage 1 ;;
        esac
    done
    shift $((OPTIND - 1))
    [ -z "$2" ] || [ -n "$3" ] && usage 1

    classdir=$1
    filename=$2
    cd $classdir || {
        echo "$0: Can't change dir to $classdir."
        exit 99
    }
    if [ -s $filename ]; then
        verbosemsg "$filename exists. Renaming to $filename.bak"
        mv $filename $filename.bak
    fi
    if [ -z "$LOGDIR" ]; then
        verbosemsg "Setting LOGDIR to default value /tmp/fai"
        LOGDIR=/tmp/fai; export LOGDIR
    fi
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# main program

PATH=.:$PATH    # so scripts in /fai/class are found
export PATH

err=0
setup "$@"
verbosemsg "fai-class: Defining classes."

echo DEFAULT | addclass

# define classes by executing scripts
# alphabetical sort is important
if [ "$debug" ]; then
    scripts=$(echo [0-9][0-9]*)
else
    scripts=$(echo [0-9][0-9]* 2>/dev/null)
fi
debugmsg "Scripts found: $scripts"

for f in $scripts ; do
    [ -f $f ] || continue # skip sockets, pipes, symlinks
    debugmsg "File $f found."
    if [ ! -x $f ]; then
        echo "Warning: File $f is not executable, so it's not used for defining classes." >&2
        continue
    fi
    classes=$(< $filename)
    export classes
    case $f in
        *~|*.bak) debugmsg "Skipping backup file $f" ;;
        *.sh)
            verbosemsg "Executing $classdir/$f."
            # this script can define $newclasses
            newclasses=
            . $f
            fc_check_status $f $?
            echo $newclasses | addclass ;;
        *.source)
            echo "ERROR: The .source suffix is deprecated. Use .sh instead." ;;
        *)
            verbosemsg "Executing $classdir/$f."
            classes=`./$f`
            fc_check_status $f $?
            if [ -f $LOGDIR/task_local_error ]; then
		lerr=$(< $LOGDIR/task_local_error)
		task_error $lerr
            fi
            echo $classes | addclass
            ;;
    esac
done

# $LOGDIR should not be writable by everybody
# scripts can also write additional classes to a file, if they
# can't print them to stdout. Define these classes.

if [ -f $LOGDIR/additional-classes ]; then
    cat $LOGDIR/additional-classes | addclass
    if [ "$debug" ]; then
        mv $LOGDIR/additional-classes $LOGDIR/additional-classes.used
    else
        # remove the file after it was used. Do not use the same file more than once.
        rm -f $LOGDIR/additional-classes
    fi
fi
if [ -z "$HOSTNAME" ]; then
     read HOSTNAME < /proc/sys/kernel/hostname
fi

# add all classes which are listed in a file with the hostname
if [ -f "$HOSTNAME" ]; then
        verbosemsg "Using classes from file $classdir/$HOSTNAME"
        grep -v "^#" $HOSTNAME | addclass
fi

echo ${ADDCLASSES//,/ } | addclass

# now add the hostname (the only class in lowercase) and LAST to
# the list of classes
echo $HOSTNAME LAST | addclass

# show all classes if verbose
debugmsg List of all classes: $(< $filename)
[ "$ctest" ] && testclass
exit $err
