#!/bin/bash
set -e
echo ""
#const
MAXMIND_BASENAME="download-maxmind.sh"
# make temp directory for storage
MAXMIND_TMPDIR="${TMPDIR:-$(dirname $(mktemp -d))/}twitch/adminpanel"
mkdir -p $MAXMIND_TMPDIR
if [ $? -ne 0 ]; then
        echo "$MAXMIND_BASENAME: Can't create temp folder $MAXMIND_TMPDIR"
        return 1
fi

# universal getter
get_quietly() {
    tmp_err=
    if [ "$(uname)" = "Darwin" ]; then
        # OSX doesn't have wget by default;
        # -s means silent output,
        # -S means don't silence errors when in silent mode,
        # --fail turns HTTP errors into actual errors instead of silent failures.
        tmp_err="`curl -x socks5h://localhost:1080 -sS --fail $1 -o "$MAXMIND_DB_FILEPATH" | awk '{ print "MM:", $0; fflush(stdout) }'`"
    else
        # Unix / anything else uses wget;
        # "Ignore all output but print output if it fails"
        # wget doesn't seem to have a sane way of only consuming its error stream,
        # as it puts a bunch of diagnostic information into stderr with no filter arg.
        tmp_err="`wget -nv $1 -O "$MAXMIND_DB_FILEPATH" | awk '{ print "MM:", $0; fflush(stdout) }'`"
    fi

    if [ $? -ne 0 ]; then
        echo $tmp_err
        echo 'MM: Fetch failed, error(s) above.'
        return 1
    else
        echo "MM: Fetch successful."
        return 0
    fi
}

#defaults
MAXMIND_TMP_FOLDER="$MAXMIND_TMPDIR/maxmind"
MAXMIND_DB_NAME='GeoIP2-City.mmdb' # / GeoIP2-ISP.mmdb
MAXMIND_REDOWNLOAD='false'
MAXMIND_FOREMAN="$(if [ -z "$FOREMAN" -o "$FOREMAN" = 'false' -o "$FOREMAN" = 'FALSE' -o "$FOREMAN" = '0' ]; then echo 'false'; else echo 'true'; fi;)"

#helper
usage()
{
echo "
Usage: $MAXMIND_BASENAME [[-d <directory>] | [-f <filename>] | [-u] | [-h]]

Options:
  -h | --help                         Show this screen.
  -d | --dir    | --directory <path>  Download directory
  -f | --file   | --filename  <file>  Database filename
  -u | --update | --no-cache          Update existing database file

Config:
  Download location: $MAXMIND_TMP_FOLDER
  Database filename: $MAXMIND_DB_NAME
  Update database?   $MAXMIND_REDOWNLOAD
  Foreman safety?    FOREMAN=$MAXMIND_FOREMAN
"
}

#cmd-line parsing
while [ "$#" -gt 0 ]; do
    case "$1" in
        -d | --dir | --directory )      shift
                                        MAXMIND_TMP_FOLDER="$1"
                                        ;;
        -f | --file | --filename )      shift
                                        MAXMIND_DB_NAME="$1"
                                        ;;
        -u | --update | --no-cache )    MAXMIND_REDOWNLOAD='true'
                                        ;;
        -h | --help )                   FINAL_HELP=1
                                        ;;
        * )                             usage
                                        return 1
    esac
    shift
done

export MAXMIND_DB_FILEPATH="$MAXMIND_TMP_FOLDER/$MAXMIND_DB_NAME"
export MAXMIND_DB_DIRECTORY="$MAXMIND_TMP_FOLDER"

#main
main(){
    if [ "$FINAL_HELP" = '1' ]; then
usage
return 0
    fi
    if [ ! -f $MAXMIND_DB_FILEPATH ] || [ "$MAXMIND_REDOWNLOAD" = "true" ]; then
echo "MM: Downloading MaxMind DB to $MAXMIND_DB_FILEPATH" && \
mkdir -p "$MAXMIND_TMP_FOLDER" && \
get_quietly "https://gen.pkgs.xarth.tv/artifactory/ip-twitch-geoip/current/$MAXMIND_DB_NAME"
    else
echo "
MM: $MAXMIND_DB_FILEPATH exists.
MM: Use -u to force an update."
    fi
echo "MM: Complete
"
return 0
}

main

if [ "$MAXMIND_FOREMAN" = "true" ]; then
$SHELL #stops the script exiting from terminating foreman
fi
