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

if [ -s "$QUEUE" ]; then
    # clean empty lines
    sed -i '/^[[:space:]]*$/d' $QUEUE
    
    # get first line
    file=$( head -n 1 $QUEUE )
    
    # Remove from queue
    sed -i "1d" $QUEUE

    # 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
    pdf_list=""
    if [[ $file == *"cover"* ]]; then
        echo "Download from $url"
        tmp_png=$tmp_dir"/cover.png"
        tmp_pdf=$tmp_dir"/cover.pdf"
        
        $CHROME \
            --print-to-pdf="$tmp_pdf" \
            "$url" &> /dev/null
        
        convert \
            -colorspace sRGB \
            -depth 8 \
            -alpha on \
            -type TrueColor \
            -quality 100 \
            -density $DENSITY \
            $tmp_pdf \
            $tmp_png
        
        convert \
            -colorspace sRGB \
            -depth 8 \
            -alpha on \
            -type TrueColor \
            -quality 100 \
            -density $DENSITY \
            $tmp_png \
            $tmp_pdf
        
        pdf_list=$tmp_pdf

    elif [[ $file == *"interior"* ]]; then
        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"
            tmp_pdf=$tmp_dir"/page_$i.pdf"
            
            $CHROME \
                --screenshot="$tmp_png" \
                --window-size=$page_width"x"$page_height \
                "$url&page=$i&dpi=$DENSITY" &> /dev/null
            
            convert \
                -colorspace sRGB \
                -depth 8 \
                -alpha on \
                -type TrueColor \
                -quality 100 \
                -density $DENSITY \
                $tmp_png \
                $tmp_pdf
            
            pdf_list=$pdf_list" "$tmp_pdf
        done
    
    elif [[ $file == *"flatten"* ]]; then
        echo "Download from $url&page=XXX&dpi=$DENSITY"
        for ((i = 1; i <= page_count; i++)); do
            echo -n $i" "
            tmp_png=$tmp_dir"/page_$i.png"
            tmp_pdf=$tmp_dir"/page_$i.pdf"
            
            $CHROME \
                --screenshot="$tmp_png" \
                --window-size=$page_width"x"$page_height \
                "$url&page=$i&dpi=$DENSITY" &> /dev/null
            
            convert \
                -colorspace sRGB \
                -depth 8 \
                -alpha on \
                -type TrueColor \
                -quality 100 \
                -density $DENSITY \
                $tmp_png \
                $tmp_pdf
            
            pdf_list=$pdf_list" "$tmp_pdf
        done

    elif [[ $file == *"pdf"* ]]; then
        echo "Download from $url"
        $CHROME \
            --print-to-pdf="$file" \
            "$url" &> /dev/null

        # Notify the client by email now that the PDF is ready
        /usr/local/cpanel/3rdparty/bin/php "$BILDR/pdf-notify.php" "$file" \
            >> "$BILDR/pdf-notify.log" 2>&1
    fi

    if [[ -n "$pdf_list" ]]; then
        gs -dSAFER \
            -dBATCH \
            -dQUIET \
            -dNOPAUSE \
            -dNOCACHE \
            -sDEVICE=pdfwrite \
            -dPDFSETTINGS=/prepress \
            -dPreserveAnnots=false \
            -sOutputFile=$file \
            $pdf_list
    fi
    
    if [[ $file != *"_cover"* && $file != *"_interior"* ]]; then
        screenshot=$( echo $file | sed "s/\.\(pdf\|jpg\)/\.jpg/" )
        tmp_pdf=$tmp_dir"/cover.pdf"
        
        $CHROME \
            --print-to-pdf="$tmp_pdf" \
            "$url&page=1" &> /dev/null
        
        convert \
            $tmp_pdf \
            -resize 320x \
            -quality 90 \
            $screenshot
        
        chmod 644 $screenshot
    fi

    # Clean up
    chmod 644 $file
    rm -rf $tmp_dir
    date

fi;
