#!/bin/bash
# -------------------------------------------------------------------
# Copyright (C) 2015 by Intevation GmbH
# Author(s):
# Sascha Wilde <wilde@intevation.de>
#
# This program is free software under the GNU GPL (>=v2)
# Read the file COPYING coming with the software for details.
# -------------------------------------------------------------------

VERBOSE=1
FORCE=0
TMPFILE=""
RECODE=/usr/bin/recode

fatal()
{
  echo >&2 "FATAL: $1"
  exit 23
}

verbose()
{
  if [ "$VERBOSE" -eq 1 ] ; then
      echo "$1"
  fi
}

convert()
{
  FILE="$1"
  TMPFILE=`mktemp "${FINE}.XXXXXXXXXX"` || fatal "Could not create temp file."

  $RECODE LATIN9..UTF8 < "$FILE" >"$TMPFILE"

  # fix access rights
  chown --reference "$FILE" "$TMPFILE"
  chmod --reference "$FILE" "$TMPFILE"

  # fix modification time
  # preserving ctime is not feasible
  # and we don't care for atime
  touch -r "$file" -m "$TMPFILE"

  # replace original file
  mv "$TMPFILE" "$file"
}

cleanup()
{
  [ -e "$TMPFILE" ] && rm "$TMPFILE"
}


# ----------------------------------------------------------------------
# Main

[ -x $RECODE ] || fatal "Could not find recode binary!"

# leave no traces...
trap cleanup EXIT

# protect temporary files
umask 077

if [ "$1" == "--force" ] ; then
    FORCE=1
    shift
fi

for file in "$@"
do
  FILE=`readlink -e -- "$file"` || fatal "Could not find $file"
  if [ $FORCE -eq 1 ] ; then
      TYPE="ISO-8859 force"
  else
    TYPE=`file -b "$FILE"`
  fi
  case "$TYPE" in
    "ISO-8859 "*)
      verbose "CONVERTING to UTF-8: ${FILE}"
      convert "$FILE"
      ;;
    *"TeX"*" document, ISO-8859"*)
      verbose "ISO-8859 LaTeX document, please adjust inputencoding/style and run:"
      verbose "`basename $0` --force ${FILE}"
      ;;
    "UTF-8 Unicode "*|"ASCII "*|*"TeX"*" document, UTF-8 Unicode"*|*"TeX"*" document, ASCII "*)
      verbose "Already UTF-8 (or ASCII): ${FILE}"
      ;;
    *)
      fatal "unknown text file type for $FILE: $TYPE"
      ;;
  esac
done
