#!/bin/bash

if [[ -z "$1" ]]; then
  echo "add-short-desc deu-eng.dict ... automatically add short description for Goldendict"
  echo "add-short-desc deu-eng.dict.dz ... will unpack into deu-eng.dict first and later rename to .orig"
  echo ".dict and .dict.orig files can be deleted afterwards"
  echo ".dict.dz file will contain newly packed dicitionary with short description"
  echo ".dict.dz.orig file, if it did not already exist, will contain backup of original .dict.dz"
  echo
  exit 0
fi

if [[ "$1" =~ .*[.]dict.dz$ ]]; then
  unpacked="${1%.dz}";
  if [[ -e "$unpacked" ]]; then
    echo "error: file already exists: $unpacked" >&2;
    exit 2;
  fi
  zcat "$1" >"$unpacked"
  set -- "$unpacked"
fi

if [[ "$1" =~ .*[.]dict$ ]]; then
  if ! [[ -e "$1.orig" ]]; then
    if head -n 10 "$1" | grep -q "^00-database-short$"; then
      echo "error: dictionary already has short name" >&2;
      exit 2;
    fi
    mv -i "$1" "$1.orig"
    head -n 10 "$1.orig" | sed $'/00-database-dictfmt-[0-9.]*/,10{/^[^0].*/{s#.*#     &#;i\\00-database-short\nq}}' >"$1"
    let lines=$(wc -l "$1"|cut -f 1 -d " ");
    { for((i=1;i<lines;i++));do read; done; cat; } <"$1.orig" >>"$1";
  else
    echo "error: file already exists: $1.orig" >&2
    exit 2;
  fi
else
  echo "error: must specify .dict file" >&2
  exit 2;
fi

target="$1.dz";
if [[ -e "$target" ]]; then
  echo "$target already exists; trying to rename to $target.orig" >&2;
  if [[ -e "$target.orig" ]]; then
    echo "$target.orig also exists; leaving file in place" >&2;
  else 
    mv -i "$target" "$target.orig";
  fi
fi

if [[ -x "$(which dictzip)" ]]; then
  echo "using dictzip" >&2
  dictzip -k "$1"
else
  echo "using gzip" >&2
  gzip -c "$1" >"$target"
fi



