#!/bin/sh
# installation script for Japanese Wnn 4.2

DICDIR=/var/dict/Wnn

yesno() {
    local question answer

    question=$1
    while :; do
    	read answer?"${question} (y/n) [y]"
	case "${answer}" in
	[Nn]*)		return 1;;
	[Yy]*)		return 0;;
	"")		return 0;;
	esac
	echo "Please answer yes or no."
    done
}

create_wnn() {
	local uname begin gid
	uname='_wnn'
	begin=517
	while [ X`id -u $begin 2>/dev/null` == X$begin ]
	do
		begin=`expr $begin + 1`
	done
	echo "Creating user _wnn ($begin)"
	gid=`id -g bin`
	chpass -a "_wnn:*:${begin}:${gid}::::Wnn server:/root:/sbin/nologin" || exit 1
}
	
for i in japanese chinese korean
do
    case "$i" in
    japanese)
	    name=ja
	    base="$DICDIR/ja_JP"
	    sys_dirs="$DICDIR/ja_JP/pubdic $DICDIR/ja_JP/wnncons"
	    wnntouch=/usr/local/bin/wnntouch
	    wnnserver=/usr/local/bin/jserver;;
    chinese)
	    name=zh
	    base="$DICDIR/zh_CN $DICDIR/zh_TW"
	    sys_dirs="$DICDIR/zh_CN/sys $DICDIR/zh_TW/sys"
	    wnntouch=/usr/local/bin/cwnntouch
	    wnnserver=/usr/local/bin/cserver;;
    korean)
	    name=ko
	    base="$DICDIR/ko_KR"
	    sys_dirs="$DICDIR/ko_KR/sys"
	    wnntouch=/usr/local/bin/kwnntouch
	    wnnserver=/usr/local/bin/kserver;;
    esac
# no base package present yet, bail out
    [ -e $wnntouch ] || continue

    if id -u _wnn >/dev/null 2>/dev/null
    then
	echo "So, user _wnn already exists !"
    else
	echo "You need a user named _wnn"
	if yesno "Would you like to create it automatically now"; then
	    create_wnn
	else
	    echo "You still need to run /usr/local/lib/wnn/install-script"
	    echo "to finish Wnn installation later"
	    exit 0
	fi
    fi

    chown _wnn $wnnserver
    chmod u+s $wnnserver

    # base directory not yet present, bail out

    for dir in $base; do
    	if [ -d $dir ]; then
	    if [ `ls -ld $dir |awk '{print $3}'` == _wnn ]; then
	    # already installed
		continue 2
	    else
		chown -R _wnn $dir
	    fi
	else
	    echo "For a complete server, you need $name-Wnn-dict-4.2 as well"
	    continue 2
	fi
    done

    for dir in $sys_dirs; do
      $wnntouch $dir/*
    done

    for dir in $base; do
      if [ ! -d $dir/usr ]; then
	mkdir -p $dir/usr
      fi
      chown _wnn $dir/usr
      chmod u+w $dir/usr
    done
done
