#!/usr/bin/env bash

GITPAGERPATH=/srv/gitpager
SCRIPTPATH=$(dirname $(realpath -s $0))

usage() {
	echo "usage: sudo ./installgitpager [prod | test]"
	exit 1
}
if [ "$EUID" -ne 0 ]; then
	echo "error: must run as root"
	usage
fi
if [ $# -eq 0 ]; then
	usage
fi
if [ "$1" != "prod" ] && [ "$1" != "test" ]; then
	usage
fi
if [ "$1" == "prod" ]; then
	NODE_ENV="production"
elif [ "$1" == "test" ]; then
	NODE_ENV="development"
fi

if [ ! -f $SCRIPTPATH/misc/gitpager.service ]; then
	echo "error: $SCRIPTPATH/misc/gitpager.service is nonexistent"
	exit 1
fi
echo "copying service file to systemd configuration folder"
cp $SCRIPTPATH/misc/gitpager.service /etc/systemd/system/gitpager.service

echo "modifying service configuration file for node environment variable"
sed -i "s/\$env/$NODE_ENV/g" /etc/systemd/system/gitpager.service

if [ -d $GITPAGERPATH/node_modules/ ]; then
	echo "preserving node_modules/ from old $GITPAGERPATH folder"
	mv -v $GITPAGERPATH/node_modules/ /tmp/gitpager_node_modules/
fi

if [ -d $GITPAGERPATH ]; then
	echo "emptying old $GITPAGERPATH folder"
	rm -r $GITPAGERPATH/*
else
	echo "creating new $GITPAGERPATH folder"
	mkdir -pv $GITPAGERPATH
fi

echo "copying $SCRIPTPATH/* to $GITPAGERPATH"
cp -r $SCRIPTPATH/* $GITPAGERPATH

echo "installing node modules at $GITPAGERPATH"
if [ -d /tmp/gitpager_node_modules/ ]; then
	mv -v /tmp/gitpager_node_modules/ $GITPAGERPATH/node_modules/
fi
npm --prefix $GITPAGERPATH install $GITPAGERPATH

echo "attempting to reload gitpager service"
systemctl daemon-reload
service gitpager restart

echo "done"