#!/bin/bash
# Example Bash shell script that downloads lecture slides (PDF)
# for ITS335, then uses pdftk to extract the slide title and number
# of pages

# Base URL for the slides
url="http://ict.siit.tu.ac.th/~sgordon/its335y14s2/slides/"

# Download the index page, which lists the PDF files
# Use the -q option to avoid displaying all the wget output
wget -q $url

# 1. Select only the lines that include pdf files
# 2. Cut each line into fields separated by " and select only 8th field
# 3. Write the .pdf file names to filelist.txt
grep "pdf" index.html | cut -d "\"" -f 8 > filelist.txt

# Loop through list of .pdf files
for f in `cat filelist.txt`;
do
	# Dispaly the file name
	echo "$f"

	# Download the PDF 
	wget -q $url$f

	# Use the dump_data operation of pdftk to display info about the file
	# The info is structured as "Field: value". 

	# 1. For the slide title, look for the InfoKey: Title, as well as 
	#    the line after it using -A 1 option of grep
	# 2. Select only the InfoValue line (which contains actual title)
	# 3. Select only the title using cut
	pdftk $f dump_data | grep -A 1 "InfoKey: Title" | grep "InfoValue" | cut -d ":" -f 2

	# 1. For the number of pages, look for NumberOfPages
	# 2. Select only the number using cut
	pdftk $f dump_data | grep "NumberOfPages" | cut -d " " -f 2

	# Delete the PDF (we only wanted the title and pages, not the actual pdf)
	rm $f
done

# Cleanup
rm filelist.txt
rm index.html
