#!/bin/bash

###################################################################
#CCCP script that fetches packets ( FILE.000 -> FILE.050 etc.. )    
#								    
#Note, the filesize must be constant, and usually it is.. the last  
#file size must be checked manually or downloaded manually..       
#								    
#This script needs the dlfetched.pl that does the actual 
#downloading. 
#
#Written by SlvWolf (slvwolf@furry.2y.net)
##################################################################


# ===== Configuration ====

# Time to wait before new search
# Note! Do _not_ enter too low value if you don't want to get banned
# from servers. 60 seconds is quite 'safe'
DELAY=60   

# ===== End =====

usage() { 
   echo "Usage: fetch FILENAME PACKETS [SIZE [LPSIZE [NFO/SVF]]]"
   echo "       FILENAME   - Base filename ie. DEV-HUM"
   echo "       SIZE       - Base filesize"
   echo "                      default 15000000"
   echo "       PACKETS    - Number of packets file.xxx, xxx = packets"
   echo "                      default 001" 
   echo "       LPSIZE     - Size of the last packet"
   echo "                      default 15000000"
   echo "       NFO/SVF    - Should .nfo and .SVF be fetched too"
   echo "                      default NO, (supported in future)"
   exit 0
}

SIZE=15000000
LPSIZE=15000000
ROUND=0
C1=-1
C2=0
C3=0
M1=1
M2=0
M3=0


if [ ! -z "$1" ] 
then
   searchquery="$1"
else
   usage
fi
if [ ! -z "$2" ]; then
	M3=`echo $2 | cut -b1`
	M2=`echo $2 | cut -b2`
	M1=`echo $2 | cut -b3`
else 
   usage
fi
if [ ! -z "$3" ]; then   
	SIZE="$3"
fi
if [ ! -z "$4" ]; then
	LPSIZE="$4"
fi
if [ ! -z "$5" ]; then
	echo "-- NFO/SVF option is not currently supported, ignoring."
fi


echo "======= Search active ======="
echo "File: $searchquery"
echo "Packets: $M3$M2$M1"
echo "Size:$SIZE"
echo "Last packet size: $LPSIZE"
echo "NFO files: Not supported"
echo "============================="


#if [ "$error" ]
#then
#  echo "Error: This kind of makes it hard to continue.. exiting."
#  exit 0
#fi

cccp -r "DONE" 

until [ "0" = "1" ]
do 
let "C1 = $C1 + 1"
echo "Starting the search - [$searchquery.$C3$C2$C1]"
if [ "$ROUND" = "0" ]; then
	if [ "$C1" = "$M1" ] && [ "$C2" = "$M2" ] && [ "$C3" = "$M3" ]; then
        cccp -gn $C3$C2$C1 $LPSIZE $searchquery.$C3$C2$C1
	else
	cccp -gn $C3$C2$C1 $SIZE $searchquery.$C3$C2$C1
	fi
fi
cccp -N -s "$searchquery.$C3$C2$C1" | perl dlfetched.pl
sleep $DELAY
if [ "$C1" = "10" ]; then
	let "C1 = 0"
	let "C2 = $C2 + 1"
	fi
if [ "$C2" = "10" ]; then
	let "C2 = 0"
	let "C3 = $C3 + 1"
	fi
if [ "$C1" = "$M1" ]; then 
if [ "$C2" = "$M2" ]; then 
if [ "$C3" = "$M3" ]; then
	let "C1 = -1"
	let "C2 = 0"
	let "C3 = 0"
	let "ROUND=1"
	fi
	fi
	fi
done

  
