#!/bin/bash
## Versio 0.3.1 - More options, more user friendly 
## Versio 0.3.0 - Uses option parser 
## Versio 0.2.1 - Prelimitary version, Correction of bug
##				that moved commentaries to preceding message 
## Versio 0.2.0 - Prelimitary version, it got rid of 
##				GNU gettext tools. Supports Uniforum 
##				output format.
## Versio 0.1.0 - Prelimitary version
##
## This is a temporary version it should be modified and 
## and made robust: file writing and opening checks.

## This sed script will mark msgstr, as comentary 
## and place it at right place (before the msgid) 
##
## This script REQUIRES Uniforum comformig files. 
## To transform your .po files use your implementation 
## of gettext tools with --strict option.

# Collect the files to be processed
LDIR=`pwd`
# Output the leading empty line
echo ""

NO_ARGS=0 
E_OPTERROR=65

if [ $# -eq "$NO_ARGS" ]  	# Script invoked with no command-line args?
then
  echo -e "\t`basename $0` validates .po files to be usable with Pootle\n"
  echo "Usage: `basename $0` options (-mnopqrs)"
  echo -e "\t-h prints this help"
  echo -e "\t-s strict - the output file is Uniforum conforming file"
  echo -e "\t-d directory - set input directory"
  echo -e "\t-f file - set input file"
  echo -e "\t-a archive msgstr - add msgstr in comentary of .po \"entry\""
  echo -e "\t-k keep - creates copy of the original .po files"
  exit $E_OPTERROR        # Exit and explain usage, if no argument(s) given.
fi  

while getopts ":saf:d:hk" Option
do
  case $Option in
    s     ) 
		strict=1;
		echo "Strict option -s was selected the output file will be Uniforum.";; 			 #   [OPTIND=${OPTIND}]";;
    a     ) 
		archive=1; 
		echo "Archive msgstr option was selected, the msgsrt will be added to commentary.";; #   [OPTIND=${OPTIND}]";;
    f     ) 
		if [[ -n "$OPTARG" ]]; then 
		  echo "The -f option requires file as parameter"
          exit 1
		fi
	    file="$OPTARG";;
    d     ) 
		if [[ -n "$OPTARG" ]] || ![[ -d "$OPTARG" ]]; then 
		  echo "The -d option requires directory as parameter"
          exit 1
		fi
		dir="$OPTARG";;
	h     ) echo "Print this help";;
	k	  ) 
		keep=1;
		echo "The option -k creates copy of original files";; 
    *     ) echo "Unimplemented option chosen.";;   # DEFAULT
  esac
done

shift $(($OPTIND - 1))

if [[ -z "$file" ]] && [[ -z "$dir" ]]; then 
  if [[ -d "$1" ]]; then
    dir="$1"
    echo -e "\nDirectory $dir was speccified\n"
    files=(`find "$dir" -name "*po"`)
    if [[ -z "$files" ]]; then
	  echo -e "No .po files found in \"$dir\"\n"
	fi
  elif [[ -f "$1" ]]; then
    files="$1";
  else 
    echo "Set file or directory to process" 
  fi
elif [[ -n "$dir" ]]; then
  echo -e "\nDirectory $dir was speccified\n"
  files=(`find "$dir" -name "*po"`)
  if [[ -z "$files" ]]; then
    echo -e "No .po files found in \"$dir\"\n"
  fi
elif [[ -n "$file" ]]; then
  files="$file";
else
  echo -e "\n\tThe argument is not a file or directory!\n"
  echo -e "\tPlease specify a .po file or a directory"
  echo -e "\twhich contains .po files to be proccesed.\n"
  exit 1
fi

# Process all the collected files
for filename in "${files[@]}"; do
  old_filename=${filename/.po/_old.po}
#  new_filename=${filename/.po/_val.po} 	# For debugging, creates new file
  tmp_filename=${filename/.po/_tmp.po}
  tmp_filename1=${filename/.po/_tmp1.po}
#  tmp_filename2=${filename/.po/_tmp2.po}

  echo "Processing file ${filename}..."
 
  # Making a copy of original file
  cp "$filename" "$old_filename"
  
  # Making the file Uniforum .po file compliant.
  cat "$filename" | sed -e '/^msgid/ i\
#
' > $tmp_filename
  
  # Adding control sequence '###' at end of each
  # .po "entry".
  cat "$tmp_filename" | sed -e '/^msgstr/,/^#/ {
   /^#/ i\
###
  }' > $tmp_filename1

  # Adding "numbersign" at the end of file.
  echo "###" >> $tmp_filename1

  # This sed script will mark "msgstr" as 
  # commentary and move it before "msgid": 
  #   First command group clears buffer 
  #   Second 
  #
  # The first sed script marks the files as #| 
  # old untranslated string. The second 
  if [[ "$archive" == "1" ]]; then 
     cat "$tmp_filename1" | sed -e '/^msgstr/,/^###/ {
      /^msgstr/ {
        x
        s/.*//
        x
      }
      H
      /^###$/ {
        x
        s/\(\n\)/\1#| /gp
        x
      }
     }' | sed -e '/^msgid/,/^###$/ {
        /^msgid/ {
          x
          s/.*//
          x
        }
        /^#/ !{
          H
          d
        }
        /^###$/ {
          x
          p
          x
        }
     }' > "$tmp_filename"
  else 
     cp "$tmp_filename1" "$tmp_filename"
  fi 

  # Creating the final .po file 
  # gmsguniq "$tmp_filename1" > "$tmp_filename"
  
  # Clearing the file: 
  #   * 	GNU getgext tool garbles original untranslated 
  #			text marged "#|" to "# |".
  #	  *		Further the artefact "#| #" from first sed script
  #			is corrected to correct commentary terminator "#"
  #   *     Correcting missing after untranslated strings:  msgstr"" 
  if [[ "$strict" == "1" ]]; then 
     # Uniforum conforming .po message
     #   *     Removing all clear lines
     cat "$tmp_filename" | sed -e 's/^#| ###$/#/' -e 's/^# |/#|/' -e '/^[ ^I]*$/ d' -e 's/^###$/#/' > "$filename"
  else
     cat "$tmp_filename" | sed -e 's/^#| ###$/#/' -e 's/^# |/#|/' -e '/^[ ^I]*$/ d' -e 's/^###$//' -e 's/^msgstr[ ^J]*$/msgstr ""/' > "$filename"
     # echo "convert to normal"
  fi


  
  if [[ -s "$filename" ]]; then 
     echo "The modified file $filename was succesfuly created"
  else 
     echo -e "\tERROR, failed to create ${filename}"
	 echo -e "\tCheck the proper format of original file: ${old_filename}"
	 echo -e "\tValid Uniforum .po files are required!"
  fi

  # GNU tools based file verification 

  if [[ `gmsgcmp -m $filename $old_filename 2>&1` != "" ]]; then 
     echo -e "WARNING: Error in verification using GNU tools\n"
  else 
     echo -e "The .po file was verified using gmsgcmp\n"
  fi
  
  # Clearing temporary files 
  rm "$tmp_filename" "$tmp_filename1"					
  if [[ "$keep" != "1" ]]; then 
    rm "$old_filename"
  fi
done
