#!/bin/bash

DIE() {
    eos-color error 2
    echo -e "==> Error [$progname]:\n    $1" >&2
    eos-color reset 2
    [ "$2" ] && exit "$2" || exit 1
}

Main() {
    local -r progname=${0##*/}
    local subdir="$1"
    local dir=""
    local data
    local files=()
    local dates=()
    local sizes=()
    local ix count
    local HELLO=""
    local URLBASE=""
    local ACCOUNT=""
    local PASSWORD=""
    local APP="wget"
    local -r sep="§"

    # shellcheck disable=1091
    source "$HOME/.config/fetch-iso.conf" || return 1

    if [ -z "$HELLO" ] ; then
        if [ "$ACCOUNT$PASSWORD" ] ; then
            HELLO="$ACCOUNT:$PASSWORD"
        else
            DIE "No account/password"
        fi
    fi

    case "$subdir" in
        "") dir="$URLBASE" ;;
        *)  dir="$URLBASE/$subdir" ;;
    esac

    case "$APP" in
        curl) data=$(/bin/curl --fail -Lsm 30 -o- -u "$HELLO" "$dir")                      || DIE "Failed fetching the info page '$dir'." "$?" ;;
        wget) data=$(/bin/wget -qO - --user "${HELLO%:*}" --password "${HELLO#*:}" "$dir") || DIE "Failed fetching the info page '$dir'." "$?" ;;
    esac
    echo "$data" > /tmp/foo1
    data=$(echo "$data" | grep -P 'alt="\[   \]"|alt="\[DIR\]"|alt="\[TXT\]"')
    echo "$data" > /tmp/foo

    # directories
    local dirs=() tmp=() tmp2

    echo "/ (site's root dir)"
    tmp2="$(echo "$data" | grep 'alt="\[DIR\]"')"

    # extract "name" and "last-modification-time":
    tmp2="$(echo "$tmp2" | sed -E -e "s|.*\"indexcolname\"><a href=\"([^\"]+)\".*\"indexcollastmod\">([^<]+)<.*|\1$sep\2|g" -e 's|[ ]*$||')"

    # remove file/dir names:
    #    1) starting with dot (".")
    #    2) "archive/"
    tmp2="$(echo "$tmp2" | grep -Pv "^\.|^archive/")"

    readarray -t tmp < <(echo "$tmp2")

    [ "${tmp[0]}" ] && dirs+=("${tmp[@]}")
    count=${#dirs[@]}
    if [ "$count" -gt 0 ] ; then
        for ((ix=0; ix<count; ix++)) ; do
            echo "${dirs[$ix]}"
        done | PrettyPrint                           # output info about directories
    fi

    # files
    local unit sz
    data="$(echo "$data" | grep 'alt="\[   \]"')"
    readarray -t files < <(echo "$data" | sed -E -e 's|.*"indexcolname"><a href="([^"]+)".*|\1|g')
    readarray -t dates < <(echo "$data" | sed -E -e 's|.*"indexcollastmod">[ ]*([^<]+)<.*|\1|g' -e 's|[ ]*$||')
    readarray -t sizes < <(echo "$data" | sed -E -e 's|.*"indexcolsize">[ ]*([^<]+)<.*|\1|g'    -e 's|[ ]*$||')
    count=${#files[@]}
    if [ "$count" -gt 0 ] ; then
        for ((ix=0; ix<count; ix++)) ; do
            sz="${sizes[$ix]}"
            unit="${sz: -1}"
            if true ; then
                case "$unit" in
                    G | M | K) sz="${sz:: -1} ${unit}B" ;;
                    [0-9])     sz+=" B" ;;
                esac
            fi
            echo "${files[$ix]}$sep${dates[$ix]}$sep$sz"
        done | PrettyPrint                           # output info about files
    fi
}

PrettyPrint() { column -t -s"$sep" | sort -k2 -k3 ; }

Main "$@"
