#!/bin/sh
##
## Dump NIS+ tables into (/etc file style) text files
##
## Author: SATOH Fumiyasu @ OSS Technology Co., Japan
## Date: 2006-03-07, since 2006-03-03
##

set -u
umask 077

PATH="/sbin:/usr/sbin:/usr/lib/nis:/bin:/usr/bin:$PATH"
export PATH

cmd_usage="Usage: $0 [OPTIONS] DIR

Options:
 -d, --domain NAME
    Specify NIS+ domainname
 -e, --exclude NAME
    Exclude specified NAME table
 -m, --mask-password CHAR
    Mask password hash by CHAR in passwd table

Arguments:
 DIR
    Destination directory
"

nisdomain=""
nisaddent_cmd="nisaddent"
mask_password=""

table_list="
    aliases
    bootparams
    ethers
    group
    hosts
    ipnodes
    netgroup
    netid
    netmasks
    networks
    passwd
    protocols
    publickey
    rpc
    sendmailvars
    services
    shadow
    timezone
    auto_home
    auto_master
"

for table in $table_list; do
    eval "exclude_$table="
done

while test "$#" -gt 0; do
    opt="$1"; shift
    test x"$opt" = x"--" && break
    case "$opt" in
    -d|--domain)
	if [ "$#" -eq 0 ]; then
	    echo "$0: option requires an argument: $opt" 1>&2
	    exit 100
	fi
	nisdomain="$1"; shift
	;;
    -e|--exclude)
	if [ "$#" -eq 0 ]; then
	    echo "$0: option requires an argument: $opt" 1>&2
	    exit 100
	fi
	if expr _"$1" : _".*[^a-z_]" >/dev/null; then
	    echo "$0: illegal table name: $1" 1>&2
	    exit 100
	fi
	eval "exclude_$1=yes"; shift
	;;
    -m|--mask-password)
	if [ "$#" -eq 0 ]; then
	    echo "$0: option requires an argument: $opt" 1>&2
	    exit 100
	fi
	mask_password="$1"; shift
	;;
    --nisaddent)
	if [ "$#" -eq 0 ]; then
	    echo "$0: option requires an argument: $opt" 1>&2
	    exit 100
	fi
	nisaddent_cmd="$1"; shift
	;;
    -h|--help)
	echo "$cmd_usage"
	exit 0
	;;
    -*)
	echo "$0: illegal option: $opt" 1>&2
	echo "$cmd_usage"
	exit 100
	;;
    *)
	set -- "$opt" ${1:+"$@"}
	break
	;;
    esac
done

if [ $# -ne 1 ]; then
    echo "$cmd_usage"
    exit 0
fi

dst_dir="$1"; shift
if [ ! -d "$dst_dir" ]; then
    echo "$0: destination directory does not exist: $dst_dir" 1>&2
    exit 100
fi

if type "$nisaddent_cmd" >/dev/null 2>&1; then
    :
else
    echo "$0: command not found: $nisaddent_cmd" 1>&2
    exit 100
fi

for table in $table_list; do
    eval "test -n \"\$exclude_$table\"" && continue

    dst="$dst_dir/$table"
    if [ -f "$dst" ]; then
	echo "$0: destination file already exists: $dst" 1>&2
	continue
    fi

    if [ x"$table" = x"sendmailvars" ] || expr "$table" : "auto_" >/dev/null; then
	"$nisaddent_cmd" -d -t "$table.org_dir" key-value $nisdomain >"$dst"
#   elif [ x"$table" = x"mail_aliases" ]; then
#	"$nisaddent_cmd" -d -t "$table.org_dir" aliases $nisdomain >"$dst"
    elif [ x"$table" = x"shadow" ] && [ -n "$mask_password" ]; then
	"$nisaddent_cmd" -d "$table" $nisdomain \
	|awk 'BEGIN {FS=":"; OFS=":"} {$2="'"$mask_password"'"; print}' \
	>"$dst"
    else
	"$nisaddent_cmd" -d "$table" $nisdomain >"$dst"
    fi
done

exit 0

