#!/bin/sh
set -e
#
# Perform necessary firezone setup steps
# before package is installed.
#

kernelCheck() {
  major=`uname -r | cut -d'.' -f1`
  if [ "$major" -lt "5" ]; then
    echo "################################################################################"
    echo "# ERROR: Kernel version `uname -r` is not supported. Firezone requires         #"
    echo "# kernel >= 5 or higher. See our listed of supported platforms for more        #"
    echo "# information: https://docs.firezone.dev/deploy/supported-platforms/         #"
    echo "################################################################################"
    exit
  fi
}

configCheck() {
  config_file='/etc/firezone/firezone.rb'

  if tput setaf 1; then
    error=$(tput setaf 1)
  else
    error=''
  fi
  if tput sgr0; then
    normal=$(tput sgr0)
  else
    normal=''
  fi

  if test -f $config_file && grep -q "^\s*default\['firezone'\]\['authentication'\]\['\(google\|okta\)'\]\['enabled'\]\s*=\s*true" $config_file ; then
    echo "${error}ERROR: Firezone 0.5+ disables support for pre-configured Okta and Google OAuth2 providers!${normal}"
    echo "Please see our transition guide to move to a generic OIDC config: https://docs.firezone.dev/administer/upgrade#upgrading-from--050-to--050"
    exit 1
  fi

  if test -f $config_file && grep -q "^\s*default\['firezone'\]\['nginx'\]\['force_ssl'\]\s*=\s*false" $config_file ; then
    echo "${error}ERROR: Firezone 0.5+ removes support for disabling SSL redirect!${normal}"
    echo "Instead, disable Nginx and point your SSL-terminating proxy directly to the phoenix app on port 13000. See the docs for more information: https://docs.firezone.dev/deploy/reverse-proxies"
    exit 1
  fi
}

capture () {
  if type curl > /dev/null; then
    if [ -e /var/opt/firezone/cache/telemetry_id ]; then
      telemetry_id=`cat /var/opt/firezone/cache/telemetry_id`
      if [ ! -z "$telemetry_id" ]; then
        curl -s -XPOST \
          -m 5 \
          -H 'Content-Type: application/json' \
          -d "{
            \"api_key\": \"phc_ubuPhiqqjMdedpmbWpG2Ak3axqv5eMVhFDNBaXl9UZK\",
            \"event\": \"preinst\",
            \"properties\": {
              \"distinct_id\": \"$telemetry_id\"
            }
          }" \
          https://t.firez.one/capture/ > /dev/null
      fi
    fi
  fi
}
if [ ! -e /var/opt/firezone/.disable_telemetry ]; then
  capture || true
fi

kernelCheck
configCheck
echo "You're about to install firezone!"
