#!/bin/bash

TIMESTAMP=`date -u +%Y-%m-%dT%H:%M:%S.000Z`
CRAWL_DIR="/var/lib/nutch/crawl"
# NUMBER OF PAGES PER PASS
TOPN=10000
# NUMBER OF PASSES
LIMIT=50
# SEND ERROR MESSAGES TO
ERROR_EMAIL="butch@tcg.com"

cd /opt/nutch/apache-nutch-1.6
echo "starting a new crawl at " $TIMESTAMP

# remove the old crawl
rm -rf $CRAWL_DIR


#cd /opt/nutch
export JAVA_HOME=/usr/lib/java/
export NUTCH_HEAPSIZE=2000
export HADOOP_HEAPSIZE=2000

# Update the blacklist
/opt/nutch/update_url_filter.pl > /opt/nutch/apache-nutch-1.6/conf/regex-urlfilter.txt

# First get the latest seeds
wget http://www.nitrc.org/search/nutch_seeds.php -O /var/lib/nutch/seed/urls

if [ $? -ne 0 ]
then
 exit;
fi

#
# Do initial crawl
# ./bin/crawl /var/lib/nutch/seed $CRAWL_DIR http://localhost:8983/solr/ 30
#./bin/nutch crawl /var/lib/nutch/seed -dir $CRAWL_DIR -depth 1 -threads 10 -topN 5000
#./bin/nutch crawl /var/lib/nutch/seed -dir $CRAWL_DIR -depth 2 -threads 5 -topN 50
#
# if [ $? -ne 0 ]
# then
#  echo "Nutch Crawl Failed" | mail -s "Nutch Crawl Failed" $ERROR_EMAIL;
#  exit;
# fi
#
# Sdd to Solr index
# ./bin/nutch solrindex http://localhost:8983/solr/ $CRAWL_DIR/crawldb -linkdb $CRAWL_DIR/linkdb $CRAWL_DIR/segments/* -deleteGone -filter -normalize
#
# if [ $? -ne 0 ]
# then
#  echo "Nutch Index Failed" | mail -s "Nutch Index Failed" $ERROR_EMAIL;
#  exit;
# fi
#


#######################################################
# The following is modified taken from bin/crawl
# Crawl in small segments to avoid memory issues
#######################################################


SEEDDIR="/var/lib/nutch/seed"
CRAWL_PATH="$CRAWL_DIR"
SOLRURL="http://localhost:8983/solr/"

# set the number of slaves nodes
numSlaves=1

# and the total number of available tasks
# sets Hadoop parameter "mapred.reduce.tasks"
numTasks=`expr $numSlaves \* 2`

# number of urls to fetch in one iteration
# 250K per task?
sizeFetchlist=`expr $numSlaves \* $TOPN`

# time limit for feching
timeLimitFetch=180

# num threads for fetching
numThreads=50

#############################################

# determines whether mode based on presence of job file

mode=local
if [ -f ../nutch-*.job ]; then
    mode=distributed
fi

bin="./bin"

# note that some of the options listed here could be set in the 
# corresponding hadoop site xml param file 
commonOptions="-D mapred.reduce.tasks=$numTasks -D mapred.child.java.opts=-Xmx1000m -D mapred.reduce.tasks.speculative.execution=false -D mapred.map.tasks.speculative.execution=false -D mapred.compress.map.output=true"

 # check that hadoop can be found on the path 
if [ $mode = "distributed" ]; then
 if [ $(which hadoop | wc -l ) -eq 0 ]; then
    echo "Can't find Hadoop executable. Add HADOOP_HOME/bin to the path or run in local mode."
    exit -1;
 fi
fi

# initial injection
$bin/nutch inject $CRAWL_PATH/crawldb $SEEDDIR

if [ $? -ne 0 ] 
  then
  echo "Nutch Inject Failed" | mail -s "Nutch Crawl Failed" $ERROR_EMAIL;
  exit $? 
fi


# main loop : rounds of generate - fetch - parse - update
for ((a=1; a <= LIMIT ; a++))
do
  if [ -e ".STOP" ]
  then
   echo "STOP file found - escaping loop"
   break
  fi

  echo `date` ": Iteration $a of $LIMIT"

  echo "Generating a new segment"
  $bin/nutch generate $commonOptions $CRAWL_PATH/crawldb $CRAWL_PATH/segments -topN $sizeFetchlist -numFetchers $numSlaves -noFilter
  
  if [ $? -ne 0 ] 
  then 
    echo "Nutch Generate Failed" | mail -s "Nutch Crawl Failed" $ERROR_EMAIL;
    exit $? 
  fi

  # capture the name of the segment
  # call hadoop in distributed mode
  # or use ls

  if [ $mode = "local" ]; then
   SEGMENT=`ls -l $CRAWL_PATH/segments/ | sed -e "s/ /\\n/g" | egrep 20[0-9]+ | sort -n | tail -n 1`
  else
   SEGMENT=`hadoop fs -ls $CRAWL_PATH/segments/ | grep segments |  sed -e "s/\//\\n/g" | egrep 20[0-9]+ | sort -n | tail -n 1`
  fi
  
  echo "Operating on segment : $SEGMENT"

  # fetching the segment
  echo "Fetching : $SEGMENT"
  $bin/nutch fetch $commonOptions -D fetcher.timelimit.mins=$timeLimitFetch $CRAWL_PATH/segments/$SEGMENT -noParsing -threads $numThreads

  if [ $? -ne 0 ] 
  then 
    echo "Nutch Fetch Failed" | mail -s "Nutch Crawl Failed" $ERROR_EMAIL;
    exit $? 
  fi

  # parsing the segment
  echo "Parsing : $SEGMENT"
  # enable the skipping of records for the parsing so that a dodgy document 
  # so that it does not fail the full task
  skipRecordsOptions="-D mapred.skip.attempts.to.start.skipping=2 -D mapred.skip.map.max.skip.records=1"
  $bin/nutch parse $commonOptions $skipRecordsOptions $CRAWL_PATH/segments/$SEGMENT

  if [ $? -ne 0 ] 
  then 
    echo "Nutch Parse Failed" | mail -s "Nutch Crawl Failed" $ERROR_EMAIL;
    exit $? 
  fi

  # updatedb with this segment
  echo "CrawlDB update"
  $bin/nutch updatedb $commonOptions $CRAWL_PATH/crawldb  $CRAWL_PATH/segments/$SEGMENT

  if [ $? -ne 0 ] 
  then 
    echo "Nutch UpdateDB Failed" | mail -s "Nutch Crawl Failed" $ERROR_EMAIL;
    exit $? 
  fi

# note that the link inversion - indexing routine can be done within the main loop 
# on a per segment basis
  echo "Link inversion"
  $bin/nutch invertlinks $CRAWL_PATH/linkdb $CRAWL_PATH/segments/$SEGMENT

  if [ $? -ne 0 ] 
  then 
    echo "Nutch InvertLinks Failed" | mail -s "Nutch Crawl Failed" $ERROR_EMAIL;
    exit $? 
  fi

  echo "Indexing $SEGMENT on SOLR index -> $SOLRURL"
  $bin/nutch solrindex $SOLRURL $CRAWL_PATH/crawldb -linkdb $CRAWL_PATH/linkdb $CRAWL_PATH/segments/$SEGMENT -filter -normalize
  
  if [ $? -ne 0 ] 
  then 
    echo "Nutch SolrIndex Failed" | mail -s "Nutch Crawl Failed" $ERROR_EMAIL;
    exit $? 
  fi

#  echo "SOLR dedup -> $SOLRURL"
#  $bin/nutch solrdedup $SOLRURL
#  
#  if [ $? -ne 0 ] 
#  then 
#    echo "Nutch Dedup Failed" | mail -s "Nutch Crawl Failed" $ERROR_EMAIL;
#    exit $? 
#  fi

done


#######################################################


# delete old documents
wget -o /dev/null -O /dev/null "http://localhost:8983/solr/update?stream.body=%3Cdelete%3E%3Cquery%3Etstamp%3A[2000-01-01T00:00:00.000Z+TO+"$TIMESTAMP"]%3C/query%3E%3C/delete%3E"

#commit changes
wget -o /dev/null -O /dev/null "http://localhost:8983/solr/update?commit=true"



