#!/bin/bash
#
#  Replaces iso8859-1 file in first arg by its utf-8 equivalent
#

if [ "$1" = "" ]; then
  echo "*** Syntax $0 iso8859-1_file"
  exit 44
  fi
  
if [ ! -w "$1" ]; then
  echo "*** '$1' doesn't exists or Can't write on '$1'"
  exit 44
  fi
  
THEDIR=`dirname "$1"`
TMPFILE="$THEDIR/{$$}_iconv"
ORGENCOD=`file "$1" | cut -d" " -f2`
if [ "$ORGENCOD" != "ISO-8859" ] ;then
  echo "*** '$1' is not iso8859-1 encoded!"
  # exit 99
  echo -n "Continue? [Y|N] "; read n;
  if [ "$n" != 'Y' ]; then echo "** ABANDON ($n)"; exit 99; fi
  fi
if [ -x /usr/bin/iconv ]; then
  iconv -f iso8859-1 -t utf8 "$1" >"$TMPFILE"
  if [ "$?" = 0 ]; then
    mv "$TMPFILE" "$1"
    if [ "$?" != 0 ]; then
      echo "*** Can't replace dest file!"
      exit 77
      fi
  else
    echo "*** iconv ERROR '$?'"
    exit 66
    fi
else
  echo "*** iconv not installed!"
  exit 55
  fi
