#!/bin/sh

# Download ISO 639-3 language table, UTF-8 version
# (c) 2018 Christian Wolff, sub-isotab@scara.com
#

FNAME="iso-639-3"
FSEP="_"
FEXT=".tab"

# Retrieve date of latest table update
DATE=`\
	wget -q -O - 'https://iso639-3.sil.org/code_tables/download_tables' | \
	perl -e 'while (<>) { if (/iso-639-3_Code_Tables_(\d{8})\.zip/) { print $1; exit 0; } }' \
	`

# Generate file name including release date
URL='https://iso639-3.sil.org/sites/iso639-3/files/downloads/iso-639-3.tab'
FILENAME=${FNAME}${FSEP}${DATE}${FEXT}

# Download table
echo Downloading ${FILENAME} from ${URL}
wget -nc -O ${FILENAME} ${URL}

# Add Unicode Byte-Order-Mark to UTF-8 file
grep $'\xEF\xBB\xBF' ${FILENAME} || sed -i '~' '1s/^/\xEF\xBB\xBF/' ${FILENAME}

# Create soft links to generic file names
#ln -sf ${FILENAME} ${FNAME}${FEXT}

# Update generic file, with backup
mv ${FNAME}${FEXT} ${FNAME}${FEXT}.bak
cp -p ${FILENAME} ${FNAME}${FEXT}

