#!/bin/sh

if [ "$(lipc-get-prop com.lab126.volumd driveModeState)" != "0" ]
then
    echo "$Kindle is in USB mass storage mode ! Refusing to run."
    exit 1
fi

fdlog() {
    echo "$(date +'%F %T'): $*" >> "$LOG_FILE"
}


display_init() {
    update_screen_info
    export EI_ROW=38
    export width=49
    [ "$SCREEN_X_RES" == "600" ] || export EI_ROW=28
    [ "$SCREEN_X_RES" == "600" ] || export width=65
}

display() {
    display_init
    [ -n "$2" ] && export EI_ROW=$(($EI_ROW-1))
    puts "$(printf "%${width}s" ' ' )"
    puts "$(printf "%-${width}s" " FD: $1" || dd bs=1 count=${width})"
    [ -n "$2" ] && puts "$(printf "%-${width}s" "$2" || dd bs=1 count=${width})"
}

BROWSER_PIPE="/var/local/log/browser_log"
PID_FILE="/var/local/browser/freedownload.pid"
FD_HOME="/mnt/base-us/freedownload"
DOWNLOAD_DIR="/mnt/base-us/documents/Downloaded"
BASE_DIR="/mnt/base-us"

MYPID="$$"

echo "$MYPID" > "$PID_FILE"


_FUNCTIONS=/etc/rc.d/functions
[ -f ${_FUNCTIONS} ] && . ${_FUNCTIONS}

_EIPUTS=/usr/sbin/eiputs
[ -f ${_EIPUTS} ] && . ${_EIPUTS}

puts_init
display_init

if [ -f "$FD_HOME/freedownload.conf" ]
then
    tr -d '\r' < "$FD_HOME/freedownload.conf" > /tmp/freedownload.conf
    mv -f /tmp/freedownload.conf "$FD_HOME/freedownload.conf"
    . "$FD_HOME/freedownload.conf"
fi



LOG_FILE=/dev/null
[ "$LOG" == "yes" ] && LOG_FILE="$FD_HOME/freedownload.log"

[ "$RESUME_DOWNLOADS" == "yes" ] && resume=" -C - "

for ext in $ALLOWED_EXTENSIONS
do
    [ -z "$uri_regex" ] || uri_regex="$uri_regex"'|'
    uri_regex="$uri_regex"'[.]'"$ext"'[.][.][.]'
done


cat "$BROWSER_PIPE" |  awk "BEGIN {FS="'"DocumentLoader::setRequest |[.][.][.]"'"} !/DocumentLoader::setRequest/ {next} /$uri_regex/ {print \$2}" | while [ -r "$BROWSER_PIPE" ]
do
    read uri
    if [ -n "$uri" ]
    then
	fname=$(basename "$uri")
	decoded_fname=$(echo "$fname" | echo -e "$(sed 's/+/ /g; s/%/\\x/g')")
	ext="${decoded_fname##*.}"
	downdir=$(eval 'echo "$DOWNLOAD_DIR_'$ext'"')
	[ -n "$downdir" ] || downdir="$DOWNLOAD_DIR"
	[ "${downdir#/}" != "$downdir" ] || downdir="$BASE_DIR/$downdir"
	[ -d "$downdir" ] || mkdir -p "$downdir"
	cd "$downdir"
	display "Downloading $decoded_fname ..." " "
	fdlog "Downloading $uri ..."
	{ curl -# -b /var/local/browser/cookies -O $resume "$uri" 2>&1; echo "$?" > /tmp/curl.ret; } | \
	    tr '\r' '\n' | \
	    sed -e 's/[.].*//g;s/^#*\s*//g' | \
	    awk 'BEGIN {lastline="100"} /.+/ && $0>lastline {lastline=$0; dots=lastline*'$width'/100; printf "%-" dots "s","."; printf "\n" }' | \
	    tr ' ' '.' | \
	    while read progress; do display "Downloading $decoded_fname ..." "$progress"; done

	if [ "$(cat /tmp/curl.ret)" == "0" ]
	then
	    display "Downloaded $decoded_fname"
	    fdlog "Downloaded $uri"
	    [ "$decoded_fname" == "$fname" ] || mv -f "$fname" "$decoded_fname"
	    fname="$decoded_fname"
	    zipbname="${fname%.zip}"
	    if [ "$zipbname" != "$fname" -a "$AUTO_UNZIP" == "yes" ]
	    then
		if unzip -l "$fname" | awk '/^\s*------/ {disp=!disp;next} disp==1 {print $4}' | grep -q '[^]/ !#$%&'"'"'()+,-.0123456789=@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[_`abcdefghijklmnopqrstuvwxyz{}~]'
		then
		    display "Not unzipped, invalid filename(s) in $decoded_fname"
		    fdlog "Not unzipped, invalid filename(s) in $decoded_fname"
		else
		    mkdir "$zipbname"
		    mv -f "$fname" "$zipbname/"
		    if cd "$zipbname"
		    then
			if unzip -qq "$fname"
			then
			    rm -f "$fname"
			    display "Unzipped $decoded_fname"
			    fdlog "Unzipped $decoded_fname"
			fi
			cd ..
		    fi
		fi
	    fi
	    dbus-send --system /default com.lab126.powerd.resuming int32:1
	else
	    display "Error while downloading $decoded_fname"
	    fdlog "Error while downloading $uri"
	fi
    else
	sleep 1
    fi
done
