BILDR="/home/insuraz1/public_html/_bildr"
ONLINE="https://www.bookbildr.com/bildr/book-load.php"
QUEUE=$BILDR"/printing.queue"
CHROME=$BILDR"/chrome-linux64/chrome --headless --no-first-run --no-sandbox --hide-scrollbars --run-all-compositor-stages-before-draw --disable-gpu --disable-application-cache --disable-cache --font-render-hinting=none"
DENSITY=300

file=/home/insuraz1/public_html/emagicum.com/bildr/media/bildr/lunadetenerife/__book_1yvtr19_lu1784247470_interior.pdf

# Check file
html=$(echo "$file" | sed -E 's/(__book_[^_]*).*?\.(pdf|jpg)/\1.html/')
if [ ! -e $html ]; then
    echo "File $html does not exist"
    exit;
fi
echo $html

# Prepare folder and file
rm -f $file
tmp_dir=$(echo "$html" | sed 's/\.html//')
rm -rf $tmp_dir
mkdir $tmp_dir

# Prepare load URL
if [[ "$file" == *"edu.bookbildr.com"* ]]; then
    ONLINE=$(echo "$ONLINE" | sed 's/www./edu./')
elif [[ "$file" == *"emagicum.com"* ]]; then
    ONLINE=$(echo "$ONLINE" | sed 's/www.bookbildr/emagicum/')
fi

IFS="/" read -r -a arr <<< $( sed "s/__book_\|\.\(pdf\|jpg\)//g" <<< $file )
url="$ONLINE?user_id=${arr[-2]}&id=${arr[-1]}"

# Get HTML data
tmp_html=$tmp_dir"/book.html"
wget -O $tmp_html "$url&preload=yes"
page_width=$(grep -in -- "--document-width:" $tmp_html | awk '{gsub(/in;/,"",$3); print int($3 * '$DENSITY')}')
page_height=$(grep -in -- "--document-height:" $tmp_html | awk '{gsub(/in;/,"",$3); print int($3 * '$DENSITY')}')
page_count=$(grep -in -- "--page-count:" $tmp_html | awk '{print int($3)}')

# Begin download and convert
date
png_list=""
echo "Download from $url&page=XXX&dpi=$DENSITY"
for ((i = 2; i < page_count; i++)); do
    echo -n $i" "
    tmp_png=$tmp_dir"/page_$i.png"
    
    $CHROME \
        --screenshot="$tmp_png" \
        --window-size=$page_width"x"$page_height \
        "$url&page=$i&dpi=$DENSITY" &> /dev/null

    png_list=$png_list" "$tmp_pdf
done
date


#const list = document.querySelectorAll('.ft-page-content');
#let loaded = 0;
#list.forEach((el, i) => {
#    const img = new Image();
#    img.src = `/bildr/media/bildr/lunadetenerife/__book_1yvtr19/page_${i + 2}.png`;
#    img.style.width = '100%';
#    img.style.height = '100%';
#    img.style.display = 'block';
#    img.onload = function() {
#        loaded++;
#        console.log(loaded + '/' + list.length);
#    }
#    el.replaceChildren(img);
#});