#!/bin/bash

#echo "Service name:"
#read SERVICE
#echo "Rabbit host:"
#read RHOST
#echo "Rabbit pass:"
#read RPASS

HELP=$(cat <<'EOF'
Missing required args:

-s - SERVICE name
-h - RabbitMQ HOST
-p - RabbitMQ PASS
EOF
)

VECTOR=$(which vector)

if [ -z $VECTOR ]; then
  echo "You need https://vector.dev to be installed"
fi

echo "VECTOR=$VECTOR"

while getopts ":s:h:p:" opt; do
  case $opt in
    s) SERVICE="$OPTARG"
    ;;
    h) RHOST="$OPTARG"
    ;;
    p) RPASS="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    exit 1
    ;;
  esac

  case $OPTARG in
    -*) echo "Option $opt needs a valid argument"
    exit 1
    ;;
  esac
done

if [ -z $SERVICE ]; then
  echo "$HELP"
  exit -1
fi
if [ -z $RHOST ]; then
  echo "$HELP"
  exit -1
fi
if [ -z $RPASS ]; then
  echo "$HELP"
  exit -1
fi

printf "SERVICE = %s\n" "$SERVICE"
printf "HOST = %s\n" "$RHOST"
printf "PASS = %s\n" "$RPASS"

FNAME="$SERVICE-logs-preparer.service"
#SERVICEFILE="/etc/systemd/system/$FNAME"
SERVICEFILE="$HOME/.config/systemd/user/$FNAME"

echo "FNAME = $FNAME"
echo "SERVICEFILE = $SERVICEFILE"

if [ -f $SERVICEFILE ]; then
  echo "Disabling current service..."
  systemctl --user stop $FNAME
  systemctl --user disable $FNAME
  systemctl --user daemon-reload
  sudo rm $SERVICEFILE
fi

echo "Creating service file..."

cat logs-preparer.service | sed 's?<DIR>?'`pwd`'?' | sed 's/<RHOST>/'$RHOST'/' | sed 's/<RPASS>/'$RPASS'/' | sed 's/<SERVICE>/'$SERVICE'/' | sed 's?<VECTOR>?'$VECTOR'?' | sudo tee -a "$SERVICEFILE" > /dev/null

echo "Reloading daemons..."

systemctl --user daemon-reload

echo "Enabling daemon for user..."

systemctl --user enable $FNAME

echo "Starting daemon for user..."

systemctl --user start $FNAME


