#!/bin/sh

SRC=$1

if [ ! -d "$SRC" ]
then
	echo "Missing vlc source repository"
	exit 1
fi

DST=$2

if [ -e "$DST" ]
then
	echo "Output file already exists"
	exit 1
fi

#######################
copy_deps() {
	local d="$1"
	local s="$2"
	local so
	local b

	for so in $(ldd "$s" | grep '=>' | sed 's/^.*=>\(.*\)(.*$/\1/')
	do
		b=$(basename "$so")
		if [ -f "$d/libs/$b" ]
		then
			continue
		fi
		#echo "Missing $b"
		copy_deps "$d" "$so"
		cp "$so" "$d/libs/"
	done
}
silent() {
	"$@" >/dev/null 2>&1
}

#######################
VERSION=$(silent cd "$SRC" ; git describe; silent cd - )

#
WTMP=$(mktemp -d)

# Create an archive
DTMP="$WTMP/tgz"
mkdir -p "$DTMP"

#
echo "Gathering executables and libraries"
cp "$SRC/bin/vlc-static" "$DTMP/"
#
mkdir -p "$DTMP/libs"
copy_deps "$DTMP" "$DTMP/vlc-static"

mkdir -p "$DTMP/plugins"
for p in $(find "$SRC" -iname "*.so")
do
	cp "$p" "$DTMP/plugins/"
	copy_deps "$DTMP" "$p"
done

# vlc script
cat > "$DTMP/vlc" << EOF
#!/bin/sh

echo "Running $VERSION"

P=\$(dirname \$0)
if [ "x\$P" = "x" ]
then
    P='.'
fi

P=\$( cd "\$P" && pwd )

LD_LIBRARY_PATH="\$P/libs"
export LD_LIBRARY_PATH

"\$P/vlc-static" --plugin-path "\$P/plugins" "\$@"
EOF
chmod "a+x" "$DTMP/vlc"

# strip
echo "Stripping"
for p in $(find "$DTMP" -iname "*.so")
do
	strip --strip-debug "$p"
done

# tar
echo "Creating archive"
tar czf "$WTMP/vlc.tgz" -C "$DTMP" .
rm -rf "$DTMP"

# run script
echo "Creating final script ($DST)"
cat > "$DST" << EOF
#!/bin/sh

PATTERN='## END OF VLC RUN CODE ##'
SRC="\$0"

for p in grep sed tail tar gzip mktemp
do
	if ! which "\$p" >/dev/null 2>&1
	then
		echo "executable '\$p' is missing !"
		exit 1
	fi
done

OFFSET=\$(( \$(grep -b -o --binary --text -m 1 "^\$PATTERN" "\$SRC" |sed 's/^\\([0-9]*\\):.*/\1/') + \${#PATTERN} + 1 + 1 ))

DST=\$(mktemp -d)

tail -c +\$OFFSET "\$SRC" | tar xz -C "\$DST"

"\$DST/vlc" "\$@"

rm -rf "\$DST"

exit
## END OF VLC RUN CODE ##
EOF

cat "$WTMP/vlc.tgz" >> "$DST" 
chmod "a+x" "$DST"

# Clean up
rm -rf "$WTMP"

