#!/usr/bin/env bash

SCRIPTPATH=$(dirname $(realpath -s $0))

usage() {
	echo "usage: sudo ./copynginx [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 [ ! -f $SCRIPTPATH/nginx.conf ]; then
	echo "error: $SCRIPTPATH/nginx.conf is nonexistent"
	exit 1
fi
echo -e "copying nginx.conf"
cp -v $SCRIPTPATH/nginx.conf /etc/nginx/nginx.conf

if [ -d /etc/nginx/joshstock.in/ ]; then
	echo -e "clearing /etc/nginx/joshstock.in/"
	rm -rv /etc/nginx/joshstock.in/*
else
	echo -e "create new /etc/nginx/joshstock.in/"
	mkdir -pv /etc/nginx/joshstock.in/
fi

if [ ! -d $SCRIPTPATH/$1 ]; then
	echo -e "error: $SCRIPTPATH/$1 is nonexistent"
	exit 1
fi
echo -e "copying $1 configuration"
cp -rv $SCRIPTPATH/$1/* /etc/nginx/joshstock.in/

echo -e "attempting to reload nginx"
service nginx reload

echo -e "done"