#!/bin/bash
################################
#
# install seawolf.ip.service
#
# By Sam Wen @ 10/27/2018
#
################################

set -e

if [ "$(id -u)" -ne 0 ] ; then
  echo "This script must run under root."
  exit 1
fi

SYSTEMCTL=$(which systemctl)
if [ -z "$SYSTEMCTL" ]; then
  echo "Unable to find systemctl."
  exit 1 
fi

CURL_BIN=$(which curl)
if [ -z "$CURL_BIN" ]; then
  echo "Unable to find curl. Please install curl."
  exit 1 
fi

if [[ -f ./post-ip && -f ./seawolf.ip.service ]]; then
  DOWNLOADED=true
else
  DOWNLOADED=false
fi

if [ $DOWNLOADED == false ]; then

  UNZIP_BIN=$(which unzip)
  if [ -z "$UNZIP_BIN" ]; then
    echo "Unable to find unzip. Please install unzip."
    exit 1
  fi

  FILE='master.zip'
  DOWNLOAD_URL="https://codeload.github.com/seawolfiot/seawolf.io/zip/master"

  if [ -f "./$FILE" ]; then
    rm -f "./$FILE"
  fi

  $CURL_BIN -o $FILE $DOWNLOAD_URL

  if [ ! -f "./$FILE" ]; then
    echo "Failed to locate $FILE"
    exit 1
  fi

  if [ -d ./seawolf.io-master ]; then
    rm -rf seawolf.io-master
  fi

  $UNZIP_BIN ./$FILE

  rm -f ./$FILE

  cd ./seawolf.io-master

fi

/bin/cp post-ip /usr/local/bin/
/bin/cp seawolf.ip.service /etc/systemd/system/

if [ $DOWNLOADED == false ]; then
  cd ..
  rm -rf ./seawolf.io-master
fi

systemctl daemon-reload
systemctl start seawolf.ip.service
systemctl enable seawolf.ip.service

echo "Installation done!"
echo ""
echo "goto: http://seawolf.io/ip to get your IPs"