#!/bin/bash

TITLE="${1}"
URL="${2}"
NB_PAGE="${3}"
EXTENSION="${4}"
NB_DOWNLOAD=$(ls -Al ${TITLE} | wc -l)

## Loop
#TITLE="loop"
#URL="http://www.wallagain.cc/content/comics/one_shot_et_bonus_51778e8bc8178/17_0_loop_536fa75c5b3bb"
#NB_PAGE=56
#EXTENSION="jpg"

## Demon King
#TITLE="demon_king"
#URL="http://www.wallagain.cc/content/comics/one_shot_et_bonus_51778e8bc8178/8_0_one_shot_demon_king_51aa1473753cc/"
#NB_PAGE=24
#EXTENSION="jpg"

mkdir -p "${TITLE}"
pushd "${TITLE}"

i=1

# Ajout du "0" pour le 9 premières pages ...
while [ "${i}" -le "9" ]; do

  wget -q "${URL}"/0$i."${EXTENSION}"

  if [ $? -eq 0 ]; then # Dowload OK
    (( i++ ))
  else
    echo "0${i}.${EXTENSION} not download"
    # Gestion des doubles pages
    j=${i}
    (( j++ ))
    # If it's 0i-0j.jpg page
    wget "${URL}"/0$i-0$j."${EXTENSION}"
    # If it's 09-10.jpg page
    wget "${URL}"/0$i-$j."${EXTENSION}"
    (( i++ ))
  fi

done

while [ "${i}" -le "${NB_PAGE}" ]; do

  wget -q "${URL}"/$i."${EXTENSION}"

  if [ $? -eq 0 ]; then # Dowload OK
    (( i++ ))
  else
    echo "${i}.${EXTENSION} not download"
    # Gestion des doubles pages
    j=${i}
    (( j++ ))
    wget "${URL}"/$i-$j."${EXTENSION}"
    (( i++ ))
  fi

done

# Bilan
echo "${NB_DOWNLOAD} pages téléchargées pour ${NB_PAGE} demandées"


popd


