#!/bin/sh

[ -z "$*" ] && printf "enter(paste) number or link:" && read -r num || num=$*
num=$(printf "$num" | cut -d'/' -f5)
dir="$HOME/.cache/$num"
mkdir -p $dir
trap "rm -rf $dir;exit 0" INT HUP
pg=$(curl -s "https://nhentai.net/g/$num/1/" | sed -nE 's/.*pages">(.*)<\/span><.*/\1/p')
printf "\033[1;35m pages : $pg\n\033[1;33mDownloading..\033[0m"
for i in $(seq $pg);do
	i_t=$(printf "%03d" $i)
	url=$(curl -s "https://nhentai.net/g/$num/$i/" | sed -nE 's/.*<img src="([^"]*)".*/\1/p')
	curl -s "$url" -o "$dir/$i_t" && printf "\33[2K\r\033[1;32m $i / $pg done" || printf "\033[1;31m $i ❌\n" &
done
wait
printf "\033[2K\r\033[1;34mconcatenating pages to pdf"
convert "$dir/*" "$num.pdf" && printf "\033[2K\r\033[1;36msaved pdf as $num.pdf\nopening pdf...enjoy 😏😏\033[0m"
rm -rf $dir
