#!/bin/sh
set -e

CDB="`which cdb`" || CDB=""
if [ -z "$CDB" ]; then
	echo "${0##*/}: tinycdb's cdb command not found" >&2
	exit 1
fi

if [ $# -eq 0 ]; then
	echo "usage: ${0##*/} SKK-JISYO [SKK-JISYO-CDB]" >&2
	exit 1
fi

if [ ! -f "$1" ] || [ ! -r "$1" ]; then
	echo "${0##*/}: $1: can't read" >&2
	exit 2
fi

if [ $# -eq 1 ]; then
	set -- "$1" "$1.cdb"
fi

dir=`dirname "$2"`
tmpf=`tempfile -d "$dir" -m 0644`
trap 'rm -f "$tmpf"' EXIT INT TERM

LC_ALL=C awk '
    /^[^;]/ {
	s = substr($0, index($0, " ") + 1)
	print "+" length($1) "," length(s) ":" $1 "->" s
    }
    END {
	print ""
    }
' "$1" | "$CDB" -c -t "$tmpf" "$2"
