#! /bin/sh
#
# Copyright (c) 2010 The NetBSD Foundation, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND
# CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

set -e

# Constant to match whitespace in a regular expression.  Be aware that the
# string below contains both spaces and tabs!
WHITESPACE_RE='[ 	]*'
WHITESPACE_PLUS_RE='[ 	][ 	]*'

defs_tmpdir=${TMPDIR:-/tmp}

ui_progname=${0##*/}

ui_internal_error() {
    echo "${ui_progname}: INTERNAL ERROR IN ${*}" 1>&2
    exit 1
}

ui_error() {
    echo "${ui_progname}: ${*}" 1>&2
    exit 1
}

ui_number_to_string() {
    case ${1} in
    0) echo "zero" ;;
    1) echo "one" ;;
    2) echo "two" ;;
    *) ui_internal_error "ui_number_to_string" ;;
    esac
}

ui_require_args() {
    local command="${1}"; shift
    local count="${1}"; shift
    local min="${1}"; shift
    local max="${1}"; shift

    if [ ${max} = inf ]; then
        if [ ${count} -lt ${min} ]; then
            local str="$(ui_number_to_string ${min})"
            ui_usage_error "The '${command}' command takes ${str} or more" \
                "arguments"
        fi
    elif [ ${min} -lt ${max} ]; then
        if [ ${count} -lt ${min} -o ${count} -gt ${max} ]; then
            local min_str="$(ui_number_to_string ${min})"
            local max_str="$(ui_number_to_string ${max})"
            ui_usage_error "The '${command}' command takes between ${min_str}" \
                "to ${max_str} arguments"
        fi
    elif [ ${min} -eq ${max} ]; then
        if [ ${count} -ne ${min} ]; then
            local str="$(ui_number_to_string ${min})"
            ui_usage_error "The '${command}' command takes exactly ${str}" \
                "arguments"
        fi
    else
        ui_internal_error "ui_require_args"
    fi
}

ui_usage_error() {
    echo "${ui_progname}: ${*}" 1>&2
    usage
    exit 1
}

file_add_line() {
    local file="${1}"; shift
    local line="${1}"; shift

    if [ -f "${file}" ]; then
        ( exec 2>/dev/null; echo "${line}" >>"${file}" ) || \
            ui_error "Failed to add entry to '${file}'"
    else
        ( exec 2>/dev/null; echo "${line}" >"${file}" ) || \
            ui_error "Failed to create '${file}'"
    fi
}

file_remove_line() {
    local file="${1}"; shift
    local line="${1}"; shift

    local base=$(basename "${file}")
    local tempfile=$(mktemp "${defs_tmpdir}/${base}.XXXXXX") || \
        ui_error "Failed to create temporary file"
    grep -v "${line}" "${file}" >>"${tempfile}" || true
    if grep "${line}" "${tempfile}" >/dev/null; then
        ui_error "Failed to remove entry from '${file}'"
    fi
    if [ -s "${tempfile}" ]; then
        if cp -f "${tempfile}" "${file}" 2>/dev/null; then
            rm -f "${tempfile}"
        else
            rm -f "${tempfile}"
            ui_error "Cannot update '${file}'"
        fi
    else
        rm -f "${tempfile}" "${file}"
    fi
}

# vim: syntax=sh:expandtab:shiftwidth=4:softtabstop=4
#
# Copyright (c) 2010 The NetBSD Foundation, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND
# CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

# Default path to the shells file.
SHELLS_FILE='/etc/shells'

usage() {
    cat 1>&2 <<EOF
Usage: ${ui_progname} [-K shells_file] add <shell>
       ${ui_progname} [-K shells_file] check <shell>
       ${ui_progname} [-K shells_file] list
       ${ui_progname} [-K shells_file] remove <shell>
EOF
}

main() {
    local arg
    while getopts :K: arg; do
        case "${arg}" in
        K)
            SHELLS_FILE="${OPTARG}"
            ;;

        \?)
            ui_usage_error "Unknown option '-${OPTARG}'"
            # NOTREACHED
            ;;
        esac
    done
    shift $((${OPTIND} - 1))

    [ ${#} -gt 0 ] || ui_usage_error "No command specified"

    local command="${1}"; shift

    case "${command}" in
    add|check|list|remove)
        "do_${command}" "${@}"
        ;;
    *)
        ui_usage_error "Unknown command '${command}'"
        ;;
    esac
}

get_shells() {
    grep "^${WHITESPACE_RE}/" "${SHELLS_FILE}" | \
        sed -e "s,^${WHITESPACE_RE},," -e 's,#.*$,,'
}

has_shell() {
    local shell="${1}"; shift

    local shell
    for iter in $(get_shells "${SHELLS_FILE}"); do
        if [ "${iter}" = "${shell}" ]; then
            true
            return
        fi
    done
    false
}

require_shells_file() {
    [ -f "${SHELLS_FILE}" ] || \
        ui_error "Cannot find the shells file '${SHELLS_FILE}'"
}

validate_shell_name() {
    local shell="${1}"; shift

    case "${shell}" in
    /*)
        ;;
    *)
        ui_error "Invalid shell '${shell}'; not an absolute path name"
        ;;
    esac
}

do_add() {
    ui_require_args add ${#} 1 1
    local shell="${1}"; shift

    validate_shell_name "${shell}"
    [ -x "${shell}" ] || ui_error "Cannot add non-existent shell '${shell}'"

    if [ -f "${SHELLS_FILE}" ]; then
        has_shell "${shell}" && \
            ui_error "The shell '${shell}' is already in the database"
    fi

    file_add_line "${SHELLS_FILE}" "${shell}"
}

do_check() {
    ui_require_args check ${#} 1 1
    local shell="${1}"; shift

    validate_shell_name "${shell}"
    require_shells_file

    has_shell "${shell}"
}

do_list() {
    ui_require_args list ${#} 0 0

    require_shells_file

    local shell
    for shell in $(get_shells | sort); do
        echo "${shell}"
    done
}

do_remove() {
    ui_require_args remove ${#} 1 1
    local shell="${1}"; shift

    validate_shell_name "${shell}"
    require_shells_file

    if has_shell "${shell}"; then
        file_remove_line "${SHELLS_FILE}" \
            "^${WHITESPACE_RE}${shell}${WHITESPACE_RE}"
    else
        ui_error "The shell '${shell}' is not in the database"
    fi
}

main "${@}"

# vim: syntax=sh:expandtab:shiftwidth=4:softtabstop=4
