#!/bin/sh
# a script to work around deficiencies in current (2.0.[01])
# OpenOffice.org Calc's CSV import filter with quoted fields
# Copyleft 2005, 2006 by Michael Shigorin <mike@osdn.org.ua>

[ "$#" == 0 ] && {
	echo "$0: need one csv file as a parameter" >&2
	exit 1
}

debug() {
	[ -n "$DEBUG" ] && echo "$0: $*" >&2
}

# force LC_CTYPE to be defined
[ -z "$LC_CTYPE" ] && eval `locale 2>/dev/null | grep ^LC_CTYPE`

# maybe use ~/.fix-csv.conf too?
CONFIG="/etc/fix-csv.conf"
[ -f "$CONFIG" ] && . "$CONFIG" || {
	echo "$0: missing $CONFIG" >&2
	exit 1
}

# sane EOLs
[ "$EOLFIX" = "yes" ] && {
	dos2unix -U "$1"
	debug "dos2unix OK"
}

# fix ugly-formed quotes
[ "$SEDFIX" = "yes" -a -x "$SED" -a -f "$SEDRULES" ] && {
	SEDFILE=`mktemp` || {
		debug "mktemp sedfile failed"
		exit 2
	}
	"$SED" -f "$SEDRULES" < "$1" > "$SEDFILE" && {
		mv -f "$SEDFILE" "$1"
		debug "sed OK"
	} || {
		rm -f "$SEDFILE"
		debug "sed failed"
	}
}

# try to fix charset
[ "$CONVFIX" = "yes" -a -n "$CONV" ] && {
	CONVFILE=`mktemp` || {
		debug "mktemp convfile failed"
		exit 3
	}
	$CONV < "$1" > "$CONVFILE" && {
		mv -f "$CONVFILE" "$1"
		debug "iconv OK"
	} || {
		rm -f "$CONVFILE"
		debug "iconv failed"
	}
}

# get back insane EOLs -- OOo 2.0.1 seems to insist on that =/
[ "$EOLFIX" = "yes" ] && {
	dos2unix -D "$1"
	debug "dos2unix KO"
}
