#!/bin/bash
set -e

# This script generates index files for the directory structure
# of the apt and yum repos

: ${DOCKER_RELEASE_DIR:=$DEST}
APTDIR=$DOCKER_RELEASE_DIR/apt
YUMDIR=$DOCKER_RELEASE_DIR/yum

if [ ! -d $APTDIR ] && [ ! -d $YUMDIR ]; then
	echo >&2 'release-rpm or release-deb must be run before generate-index-listing'
	exit 1
fi

create_index() {
	local directory=$1
	local original=$2
	local cleaned=${directory#$original}

	# the index file to create
	local index_file="${directory}/index"

	# cd into dir & touch the index file
	cd $directory
	touch $index_file

	# print the html header
	cat <<-EOF > "$index_file"
	<!DOCTYPE html>
	<html>
	<head><title>Index of ${cleaned}/</title></head>
	<body bgcolor="white">
	<h1>Index of ${cleaned}/</h1><hr>
	<pre><a href="../">../</a>
	EOF

	# start of content output
	(
	# change IFS locally within subshell so the for loop saves line correctly to L var
	IFS=$'\n';

	# pretty sweet, will mimick the normal apache output
	for L in $(find -L . -mount -depth -maxdepth 1 -type f ! -name 'index' -printf "<a href=\"%f\">%f|@_@%Td-%Tb-%TY %Tk:%TM  @%f@\n"|sort|column -t -s '|' | sed 's,\([\ ]\+\)@_@,</a>\1,g');
	do
		# file
		F=$(sed -e 's,^.*@\([^@]\+\)@.*$,\1,g'<<<"$L");

		# file with file size
		F=$(du -bh $F | cut -f1);

		# output with correct format
		sed -e 's,\ @.*$, '"$F"',g'<<<"$L";
	done;
	) >> $index_file;

	# now output a list of all directories in this dir (maxdepth 1) other than '.' outputting in a sorted manner exactly like apache
	find -L . -mount -depth -maxdepth 1 -type d ! -name '.' -printf "<a href=\"%f\">%-43f@_@%Td-%Tb-%TY %Tk:%TM  -\n"|sort -d|sed 's,\([\ ]\+\)@_@,/</a>\1,g' >> $index_file

	# print the footer html
	echo "</pre><hr></body></html>" >> $index_file

}

get_dirs() {
	local directory=$1

	for d in `find ${directory} -type d`; do
		create_index $d $directory
	done
}

get_dirs $APTDIR
get_dirs $YUMDIR
