#!/bin/sh
#
#   Copyright (C) 2014 Masatake YAMATO
#
#   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.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

TINST_ROOT=

ERROR ()
{
    local status=$1
    local msg=$2
    shift 2
    echo "$msg" 1>&2
    exit $status
}

MSG_title()
{
    printf '%-70s' "${1}"
}

MSG_passed()
{
    echo passed
}

MSG_failed()
{
    echo failed
}

MSG_done()
{
    echo done
}


T_existing()
{
    local f=$1
    shift
    local op
    local r=0

    for op in "$@"; do
	case "$op" in
	    -d)
		MSG_title "The existence of $f as a directory"
		;;	    
	    -f)
		MSG_title "The existence of $f as an file"
		;;
	    -r)
		MSG_title "The read mode of $f"
		;;
	    -x)
		MSG_title "The existence of $f as an executable"
		;;
	    *)
		MSG_title "The existence of $f with $op operator"
		;;
	esac
	if [ $op ${TINST_ROOT}/$f ]; then
	    MSG_passed
	else
	    MSG_failed
	    r=$(( r + 1 ))
	fi
    done
    return ${r}
}

prepare()
{
    local srcdir=$1
    local root=$2


    MSG_title "Preparing installation tests"
    
    if ! [ -e ${srcdir}/configure ]; then
	ERROR 2 "cannot find configure script"
    fi

    mkdir -p "$root"

    if ! [ -d "$root" ]; then
	ERROR 2 "failed in directory creation: $roo"
    fi

    rm Makefile

    if ! ${srcdir}/configure --prefix=$root > /dev/null; then
	ERROR 2 "failed in running configure script $root"
    fi

    if ! [ -e Makefile ]; then
	ERROR 2 "cannot find Makefile"
    fi

    if ! make > /dev/null; then
	ERROR 2 "failed in building ctags"
    fi

    if ! make install > /dev/null; then
	ERROR 2 "failed in installing ctags"
    fi    

    MSG_done
    return 0
}

cleanup()
{
    MSG_title "Cleanup installation tests"
    MSG_done
    return 0
}

check()
{
    T_existing /bin/ctags -f -x
    T_existing /bin/readtags -f -x

    T_existing /share/man/man1/ctags.1 -f -r
}

main()
{
    local srcdir
    local root
    local status

    if [ $# = 2 ]; then
	srcdir=$1
	root=$2
	shift 2
    else
	ERROR 2 "A installation root must be given as the first argument"
    fi
    
    prepare "${srcdir}" "${root}"

    TINST_ROOT=${root}
    check
    status=$?

    cleanup "${root}"

    return $status
}

main "$@"
