#!/usr/bin/env bash
#
# installation script for xvidenc
#

# Check for root
if [ $UID != 0 ]; then
	echo "-> Login as root to install!"
	exit 1
fi

BINDIR=/usr/local/bin
DOCDIR=/usr/local/share/doc/xvidenc
MANDIR=/usr/local/man/man1

# Remove previously installed doc dirs
for i in /usr/local/share/doc/xvidenc*; do
	test -d $i && rm -rf $i
done

# make dirs if needed
for i in $BINDIR $DOCDIR $MANDIR; do
	if [ ! -d $i ]; then
		mkdir -p -m 755 $i 2>/dev/null
		if [ $? != 0 ]; then
			echo "-> Failed to make directories... exiting!"
			exit 1
		fi
	fi
done

# Copy xvidenc script & doc/man files
cp -f $(pwd)/xvidenc $BINDIR && chmod 755 $BINDIR/xvidenc
cp -f $(pwd)/man/xvidenc.1 $MANDIR && gzip -9 $MANDIR/xvidenc.1 && chmod 644 $MANDIR/xvidenc.1.gz
cp -f $(pwd)/doc/* $DOCDIR && chmod 644 $DOCDIR/*

# Make matrix dirs & copy matrix files
mkdir -p -m 755 $DOCDIR/matrices/Jawor1CD && cp -f $(pwd)/matrices/Jawor1CD/* $DOCDIR/matrices/Jawor1CD
mkdir -p -m 755 $DOCDIR/matrices/Jawor2CD && cp -f $(pwd)/matrices/Jawor2CD/* $DOCDIR/matrices/Jawor2CD

# Create uninstall script in $DOCDIR
cat<<EOF>>$DOCDIR/uninstall
#!/usr/bin/env bash

if [ \$UID != 0 ]; then
	echo "-> Login as root to uninstall!"
	exit 1
fi

rm -f $BINDIR/xvidenc
rm -f $MANDIR/xvidenc.1.gz
rm -rf $DOCDIR
echo ""
echo "-> Done"
echo "-> Thanks for using xvidenc!"
echo ""

exit 0
EOF

echo ""
echo "-> Installation successful"
echo ""
echo "-> Script is installed in $BINDIR"
echo "-> Doc files are installed in $DOCDIR"
echo "-> Matrix files are installed in $DOCDIR/matrices"
echo "-> Man page is installed in $MANDIR"
echo ""
if [ -f $DOCDIR/uninstall ]; then
	chmod 755 $DOCDIR/uninstall
	echo "If you want to uninstall the program and all of its files"
	echo "afterwards, go to the doc directory in $DOCDIR"
	echo "and run as root the 'uninstall' script"
fi
echo ""

exit 0