#! /bin/sh

if [ $# -lt 1 ]; then
  echo "usage: install-lang LANGUAGE..."
  exit 1
fi

install_langs=$(rpm --eval %_install_langs)

#if [ "$install_langs" = "all" ]; then
#  echo "all languages installed, nothing to do"
#  exit 0
#fi

if [ "$1" = "all" ]; then
  missing=all
else
  missing=
  IFS=:
  for l in "$@"; do
    found=0
    for i in $install_langs; do
      if [ "$l" = "$i" ]; then
        echo "skipping $l"
        found=1
      fi
    done
    if [ $found -eq 0 ]; then
      echo "installing $l"
      missing="$missing${missing:+:}$l"
    fi
  done
  unset IFS
fi

if [ "x$missing" = "x" ]; then
  echo "nothing missing"
  exit 0
fi

if [ "$missing" = "all" ]; then
  install_langs=all
else
  install_langs="$install_langs:$missing"
fi

echo "install_langs will be $install_langs"

if [ "$missing" = "all" ]; then
  packages=$(rpm -qa --qf '[%{FILELANGS} %{NAME}\n]' | grep -v "^ " | sort -u | cut -d' ' -f2)
else
  pattern=$(echo $missing | sed -e "s/:/\\\|/g")
  packages=$(rpm -qa --qf '[%{FILELANGS} %{NAME}\n]' | grep -v "^ " | grep "^\($pattern\)" | sort -u | cut -d' ' -f2)
fi

for p in $packages; do
  echo "reinstalling $p"
done

exit 0

echo "%_install_langs $install_langs" > /etc/rpm/macros

dir=$(mktemp -d)
pushd $dir

yumdownloader "$packages"
rpm -U --replacepkgs *.rpm
rm *.rpm

popd

rmdir $dir

