#!/bin/bash



walk_dir () {    
    shopt -s nullglob dotglob
    for pathname in "$1"/*; do
        if [ -d "$pathname" ]; then
            walk_dir "$pathname"
        else
            mydirname=$(dirname "$pathname")
            mybasename=$(basename "$pathname")
            mybasenameexcl=$(echo "$mybasename" | cut -f 1 -d '.')
            case "$pathname" in
                *.png|*.jpg)
                    docker run -ti --rm -v "$pathname":/myfile acleancoder/imagemagick-full convert /myfile -background white -alpha remove -alpha off /myfile
                    docker run --rm -it -v "$mydirname:/app" -w /app minidocks/img2pdf -o "/app/$mybasenameexcl.pdf" "/app/$mybasename"
                    printf '%s\n' "$pathname"
                    cp "$mydirname/$mybasenameexcl.pdf" /mnt/user/Inbox/paperless && cp "$mydirname/$mybasenameexcl.pdf" /mnt/user/Inbox/evernote
                    ;;
                *.htm|*.html)
                    URL=$(awk -F"url=|\" /></head>" '{print $2}' "$pathname")
                    docker run -v /mnt/user/Inbox/:/input openlabs/docker-wkhtmltopdf "$URL"  "/input/$mybasename.pdf"
                    cp -a /mnt/user/Inbox/. /mnt/user/Inbox/paperless && cp -a /mnt/user/Inbox/. /mnt/user/Inbox/evernote
                    rm -rf /mnt/user/Inbox/html/*
                    printf '%s\n' "$pathname"
                    ;;
                *.yml|*.yaml|*.xml|*.md)
                    docker run -r -v "$mydirname:/source" jagregory/pandoc  "/source/$mybasename" -f markdown -t latex  -o  "/app/$mybasename.pdf"
                    printf '%s\n' "$pathname"
                    cp "$mydirname/$mybasenameexcl.pdf" /mnt/user/Inbox/paperless && cp "$mydirname/$mybasenameexcl.pdf" /mnt/user/Inbox/evernote
                    ;;
                *)
                    cp "$pathname" /mnt/user/Inbox/paperless && cp "$pathname" /mnt/user/Inbox/evernote
                    printf '%s\n' "$pathname"
                    ;;
            esac
        fi
    done
}

mydir=/mnt/user/Inbox/scanned

walk_dir "$mydir"
chmod -R 777 /mnt/user/Inbox/
rm -rf /mnt/user/Inbox/scanned/*