#!/bin/sh 
set -e
# Checks if a package should be autobuild for an implementation
# Written by Kevin Rosenberg <kmr@debian.org>
# GPL-2 license

progname="$(basename $0)"
pversion='$Revision: 1.4 $'

usage()
{
        cat >&2 <<END
Usage: $progname impl library [OPTIONS]

$progname checks if a library should be auto-built for a 
particular implementation. It returns a status code of 0 for "yes"
and 1 for "no". Returns 2 for a usage error.

Options: 
  -h                  Print this short help message
END
}

# returns in $ab the canonical value of ab file
ab_file()
{
    file=$1
    # file exists and is empty, equivalent to yes
    if [ -e $file ] && [ ! -s $file ]; then
	ab="yes"
	return
    fi
    if [ -r $file ]; then
	first_line="$(cat $file | head -1)"
	if [ "$first_line" ]; then
	    first_line="$(echo "$first_line" | tr "[A-Z]" "[a-z]")"
	    if [ "$(expr "$first_line" : ".*\(yes\).*")" ]; then
		ab="yes"
		return
	    elif [ "$(expr "$first_line" : ".*\(no\).*")" ]; then
		ab="no"
		return
	    fi
	fi
    fi
    ab="inherit"
}

clc_bin_dir=/usr/lib/common-lisp/bin

if [ $# -lt 2 ]; then 
  echo "Error: too few arguments" >&2
  usage
  exit 2
fi

# make sure that first two arguments are not an option switch
if [ $(expr "$1" : "\(\-\)") ]; then
  echo "error: Missing implementation name"
  usage
  exit 1
fi
if [ $(expr "$2" : "\(\-\)") ]; then
  echo "error: Missing source package name"
  usage
  exit 1
fi

impl=$1
shift
source=$1
shift

ab_dir=/etc/common-lisp
impl_bin=/usr/lib/common-lisp/bin/$impl.sh

# Command line
while [ $# != 0 ]; do
    case "$1" in
        -h) usage; exit 0;              ;;
	-*) usage; exit 2;            ;;
	*)  echo "Error: extra arguments"; usage; exit 2;            ;;
    esac
    shift
done

if [ ! -x $impl_bin ]; then
  echo "$progname: can't find executable implementation script $impl_bin" >& 2
  exit 2
fi

# Check autobuilding by check for the most specific first

source_ab=$ab_dir/$impl/$source/autobuild
impl_ab=$ab_dir/$impl/autobuild
global_ab=$ab_dir/autobuild

if [ -r $source_ab ]; then
    # package's autobuild readable
    ab_file $source_ab
    if [ "$ab" = "yes" ]; then
	exit 0
    elif [ "$ab" = "no" ]; then
	exit 1
    fi
fi
# use impl default
if [ -r $impl_ab ]; then
    ab_file $impl_ab
    if [ "$ab" = "yes" ]; then
	exit 0
    elif [ "$ab" = "no" ]; then
	exit 1
    fi
fi
# Use global default
if [ -r $global_ab ]; then
    ab_file $global_ab
    if [ "$ab" = "yes" ]; then
	exit 0
    else
	exit 1
    fi
fi

echo "$progname: internal error: should never reach here" >& 2
