#!/bin/bash

usage() {
    echo "Script to download Bicleaner language packs."
    echo
    echo "Usage: `basename $0` <lang> [download_path]"
    echo "      -q              Quiet mode."
    echo "      -h              Show this help message."
    echo "      <lang>          Language code."
    echo "      [download_path] Path where downloaded language pack should be placed."
    echo "                      Default: current path."
}

invalid_url(){
    wget -S --spider -o - $1 | grep -q '404 Not Found'
}

WGETQUIET=""
TAROPS="xvf"
while getopts "qh" options
do
    case "${options}" in
        q) WGETQUIET="-q"
            TAROPS="xf";;
        h) usage
            exit 0;;
        \?) usage 1>&2
            exit 1;;
    esac
done

URL="https://github.com/bitextor/monocleaner-data/releases/latest/download"
L1=${@:$OPTIND:1}
DOWNLOAD_PATH=${@:$OPTIND+1:1}
if [ -z $L1 ];
then
    echo "Error language is mandatory: $@" 2>&1
    usage 2>&1
    exit 1
fi
if [ "$DOWNLOAD_PATH" == "" ]; then
    DOWNLOAD_PATH="."
fi

if invalid_url $URL/$L1.tgz
then
    >&2 echo $L1 language pack does not exist
else
    wget $WGETQUIET -P $DOWNLOAD_PATH $URL/$L1.tgz
    tar $TAROPS $DOWNLOAD_PATH/$L1.tgz -C $DOWNLOAD_PATH
    rm $DOWNLOAD_PATH/$L1.tgz
fi

if [ -z $WGETQUIET ]; then
    echo Finished >&2
fi
