#! /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 services file.
SERVICES_FILE='/etc/services'

# Regular expression to match a service.
SERVICE_RE='[-a-zA-Z0-9][-a-zA-Z0-9]*'
PORT_RE='[0-9][0-9]*/[a-zA-Z][a-zA-Z]*'

usage() {
    cat 1>&2 <<EOF
Usage: ${ui_progname} [-K services_file] add <name> <port> [aliases ...]
       ${ui_progname} [-K services_file] check <(name|port) | name port>
       ${ui_progname} [-K services_file] list
       ${ui_progname} [-K services_file] remove <name> <port>
EOF
}

main() {
    local arg
    while getopts :K: arg; do
        case "${arg}" in
        K)
            SERVICES_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
}

require_services_file() {
    [ -f "${SERVICES_FILE}" ] || \
        ui_error "Cannot find the services file '${SERVICES_FILE}'"
}

get_services() {
    local script=
    script="s,${WHITESPACE_RE}#.*,,g"
    script="${script};s,^${WHITESPACE_PLUS_RE},,g"
    script="${script};s,${WHITESPACE_PLUS_RE}, ,g"
    sed -e "${script}" <${SERVICES_FILE} | grep -v "^${WHITESPACE_RE}$"
}

has_service_by_name() {
    get_services | cut -d ' ' -f 1 | grep "^${1}$" >/dev/null
}

has_service_by_port() {
    get_services | cut -d ' ' -f 2 | grep "^${1}$" >/dev/null
}

has_service_by_name_and_port() {
    get_services | cut -d ' ' -f 1-2 | grep "^${1} ${2}$" >/dev/null
}

is_service_name() {
    echo "${1}" | grep "^${SERVICE_RE}$" >/dev/null
}

is_service_port() {
    echo "${1}" | grep "^${PORT_RE}$" >/dev/null
}

validate_service_name() {
    is_service_name "${1}" || ui_error "Invalid service name '${1}'"
}

validate_service_port() {
    is_service_port "${1}" || ui_error "Invalid service port '${1}'; not of" \
        "the form port/type"
}

do_add() {
    ui_require_args add ${#} 2 inf
    local service="${1}"; shift
    local port="${1}"; shift
    local aliases="${@}"

    validate_service_name "${service}"
    validate_service_port "${port}"

    if [ -f "${SERVICES_FILE}" ]; then
        has_service_by_name_and_port "${service}" "${port}" && \
            ui_error "The service '${service} ${port}' is already in the database"
        has_service_by_port "${port}" && \
            ui_error "The port '${port}' is already in the database"
    fi

    if [ -n "${aliases}" ]; then
        file_add_line "${SERVICES_FILE}" "${service} ${port} ${aliases}"
    else
        file_add_line "${SERVICES_FILE}" "${service} ${port}"
    fi
}

do_check() {
    ui_require_args check ${#} 1 2

    if [ ${#} -eq 1 ]; then
        if is_service_name "${1}"; then
            require_services_file
            has_service_by_name "${1}"
        elif is_service_port "${1}"; then
            require_services_file
            has_service_by_port "${1}"
        else
            ui_error "Invalid service name or port '${1}'"
        fi
    elif [ ${#} -eq 2 ]; then
        local service="${1}"; shift
        local port="${1}"; shift

        validate_service_name "${service}"
        validate_service_port "${port}"
        require_services_file
        has_service_by_name_and_port "${service}" "${port}"
    else
        ui_internal_error "do_check"
    fi
}

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

    require_services_file
    get_services | sort
}

do_remove() {
    ui_require_args remove ${#} 2 2
    local service="${1}"; shift
    local port="${1}"; shift

    validate_service_name "${service}"
    validate_service_port "${port}"
    require_services_file

    if has_service_by_name_and_port "${service}" "${port}"; then
        file_remove_line "${SERVICES_FILE}" \
            "^${WHITESPACE_RE}${service}${WHITESPACE_RE}${port}${WHITESPACE_RE}"
    else
        ui_error "The service '${service} ${port}' is not in the database"
    fi
}

main "${@}"

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