#!/bin/bash

# Show (a short piece of) information related to current location.
# Use a keyword to specify what info to show.

DIE() {
    echo "==> $progname: error: $1"
    exit 0
}

DumpOptions() {
    local tmp="--${lopts//,/ --}"
    tmp="${tmp//:/}"
    echo "$tmp"
}
DumpItems() {
    echo "${items[*]}"
}

Options() {
    local opts
    local lopts="help,timeout:,tolower,url:,dump-all"
    local sopts="ht:lu:"

    opts="$(/usr/bin/getopt -o=$sopts --longoptions $lopts --name "$progname" -- "$@")" || {
        Options -h
        return 1
    }

    eval set -- "$opts"

    while true ; do
        case "$1" in
            #--dump-options) DumpOptions; exit 0 ;;
            #--dump-items)   DumpItems; exit 0 ;;
            --dump-all)       DumpItems; DumpOptions; exit 0 ;;

            -t | --timeout)   timeout="$2" ; shift ;;
            -l | --tolower)   tolower=yes ;;
            -u | --url)       infourl="$2" ; shift ;;
            -h | --help)
                cat <<EOF >&2
$progname - show info about your current location

Usage: $progname [options] [location-item]

Location-item: one of
   ${items[*]}
Location-item defaults to showing all available info.

Options:
  -h, --help       This help.
  -l, --tolower    Convert letters to lower case on the output.
  -t, --timeout    Max number of seconds to wait for a response from
                   the location service (default: $timeout_default).
  -u, --url        The URL used for getting the location information.
EOF
                exit 0
                ;;
            
            --) shift ; break ;;
        esac
        shift
    done

    item="$1"

    local it
    for it in "${items[@]}" ; do
        [ "$item" = "$it" ] && break
    done
    
    [ "$item" = "$it" ] || DIE "item name must be one of: ${items[*]}"
    [ -n "$timeout" ]   || DIE "given timeout value cannot be empty"
}

Main() {
    local -r progname="${0##*/}"

    # default values
    local -r timeout_default=30
    local timeout=$timeout_default
    local tolower=no
    local item=""
    local supported_urls=(
        https://ipinfo.io
        https://ipapi.co
    )
    local infourl=""    # info source
    local url

    # supported values
    local items=(city country hostname ip loc org postal region timezone "")   # "" means: all

    Options "$@"

    source /etc/eos-script-lib-yad.conf || return 1

    [ "$infourl" ] || infourl="$EOS_LOCATION_PROVIDER_URL"

    if [ -n "$infourl" ] ; then
        # add the given url as first in list
        supported_urls=($(printf "%s\n" "${supported_urls[@]}" | grep -vw "$infourl"))
        supported_urls=("$infourl" "${supported_urls[@]}")
    fi

    for url in "${supported_urls[@]}" ; do
        case "$url" in
            https://ipinfo.io) ;;
            https://ipapi.co)
                case "$item" in
                    hostname | loc | "")
                        echo "sorry, item '$item' is not supported by url $url" >&2
                        continue
                        ;;
                esac
                ;;
            *) DIE "'$url' is not supported. See /etc/eos-script-lib-yad.conf for supported URLs" ;;
        esac

        # get and show the wanted location info

        local output=""
        output="$(LANG=C curl --fail -Lsm $timeout $url/$item)"

        if [ $? -eq 0 ] ; then
            if [ "$tolower" = "yes" ] ; then
                output=$(echo "$output" | tr '[:upper:]' '[:lower:]')
            fi
            echo "$output"
            return 0
        fi
    done

    echo "  ==> $progname: failed" >&2
    return 1
}

Main "$@"
