#!/bin/bash -
#
# Skript zum Runterladen eines www.mikrocontroller.net Threads inklusive aller Attachments.
# Vorraussetzungen sind wget und bash; unter Windows kann https://www.msys2.org/ verwendet werden.
#
# Version 2026-08-06
# Verbesserungen und Fragen bitte an <udo.krebelder@gmx.at>
#
# Der folgende Aufruf lädt den ersten Thread aus dem Jahr 2001 runter:
# ./uC_download.bash 1
#
# oder für Threads ohne Nummer:
# ./uC_download.bash https://www.mikrocontroller.net/topic/vorsichtsmassnahmen-fuer-kaeufer
#
# Der Thread ist nach dem Download im lokalen Verzeichnis
# www.mikrocontroller/topic/ gespeichert.
#

usage() { echo "usage: `basename $0` <thread-number>"; exit 1; }

test $# -gt 0 || usage;

accept_regex='(https://www.mikrocontroller.net/(topicX|forumX|assets|images)/.*)|(https://www.mikrocontroller.net/attachment/.*/.*)|(https://www.mikrocontroller.net/.*/.*page.*)|(https://www.mikrocontroller.net/favicon.ico))'

reject_regex='(https://www.mikrocontroller.net/topic/.*\?(edit|token)=.*)|(https://www.mikrocontroller.net/topic/(vote_post|merge).*)|(https://www.mikrocontroller.net/topic/.*reply_to=.*)|(https://www.mikrocontroller.net/topic/(goto_post|set_sticky_true|lock_for_guests|move|subscribe|merge|delete_post)/.*)|(https://www.mikrocontroller.net/articles/Spezial.*)'

for url in "$@"
do
    # match thread number
    [[ "${url}" =~ ^[0-9]+$ ]] && url="https://www.mikrocontroller.net/topic/$url"

    # else match www.mikrocontroller.net url
    [[ "${url}" =~ ^(https://www.mikrocontroller.net/).*$ ]] || usage
    
    # remove ?page=2 or ?goto=new#new
    url="${url%%\?*}"
    url="${url%%#*}"

    wget \
        -e robots=off \
        --waitretry=5 \
        --limit-rate=5000k \
        --quota=20m \
        -N \
        --no-if-modified-since \
        -r \
        -l50 \
        -k \
        -E \
        --accept-regex="$accept_regex" \
        --reject-regex="$reject_regex" \
        "$url" 

    file="${url#https://}"
    #file="${file/\?/@}"
    #echo $file

    for f in "${file}"*
    do
        #echo "Remove ad-scripts: $f"
        sed -i -r 's/script (async=.async. )?src=.((https|...assets).*\.js)./script \1src="X\2"/' "$f"
    done

    title="$(sed -n 's/<meta property="og:title" content="\([^"]*\)">/\1/p' "$file.html")"
    #echo "[$title]"
    ( cd www.mikrocontroller.net/topic && ln -s "${file##*/}.html" "$title.html" )

done
