#!/bin/sh

# setup directories
DIR="$HOME/IMAGE"
COOKIE="$DIR/cookies.txt"
mkdir -p "$DIR"

# mask requests
UA="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36"

# add pictures from log
ssh shell.codevoid.de tail -n 80000 -f .irssi/url \
| grep -i http \
| while read line;
do
    local C=$(tput cols)
    local URL=$(printf '%s' "$line" | sed 's,.*\(http[^ ]*\),\1,g')
    local TMP="$DIR/$(sha1 -qs "$URL")"
    local MIME=""

    # set the short URL to max terminal width
    local SURL=$(printf '%s' "$URL" \
           | awk -vC="$C" '{ line=substr($0,1,C-21) }
           { if (length($0) > C-21) print line"..."; else print $0 }')

    # check if file has been handled previously
    if stat -qnf "" "$TMP"* 2>&1 > /dev/null; then
        printf '↷ (in cache)	[%s]\n' "$SURL"
    else
        local MIME=$(curl -A "$UA" --connect-timeout 5 -sI "$URL" \
                    | grep -i "content-type:" | cut -d" " -f2 \
                    | cut -d";" -f1 |  tr -d '\r')
        local EXT=${MIME##*/}
        case "$MIME" in
            image/*)
                printf '⇊ (%s)	[%s]\n' "$MIME" "$SURL"
                curl -Lc "$COOKIE" -b "$COOKIE" -A "$UA" \
                     -s "$URL" > "$TMP.$EXT"
            ;;
            *)
                if [ "$MIME" == "" ]; then MIME="???/???"; fi
                printf '↷ (%s)	[%s]\n' "$MIME" "$SURL"
                if [[ x"$EXT" != "x" ]]; then
                    touch "$TMP.$EXT"
                else
                    touch "$TMP.unknown"
                fi
            ;;
        esac
    fi
done
