#!/bin/bash

if [ $(whoami) != 'root' ]; then
    echo "Must be root to run. Try using 'sudo'."
    exit 1
fi

# Verify platform architecture (amd64, arm64)
ARCH=`dpkg --print-architecture`
if [ $ARCH != "amd64" ] && [ $ARCH != "arm64" ]; then
    echo "Your detected system architecture ($ARCH) is not supported by this installation script."
    echo "Please contact DriveStrike support: support@drivestrike.com"
    exit 1
fi
echo "Platform architecture is $ARCH"

# Ensure we can access https package repositories
apt-get install -y apt-transport-https

# Get the repository public key
KEY_CMD=""
which curl > /dev/null
if [ $? -eq 0 ]; then
    KEY_CMD="curl -L https://app.drivestrike.com/static/drivestrike.pubkey.gpg -o /etc/apt/trusted.gpg.d/drivestrike.gpg"
fi
if [ -z "$KEY_CMD" ]; then
    which wget > /dev/null
    if [ $? -eq 0 ]; then
        KEY_CMD="wget https://app.drivestrike.com/static/drivestrike.pubkey.gpg -O /etc/apt/trusted.gpg.d/drivestrike.gpg"
    fi
fi
if [ -z "$KEY_CMD" ]; then
    echo ""
    echo "ERROR: This script requires that curl or wget, but neither was found."
    echo "  Please install one of these and re-run this script."
    echo "  e.g.: sudo apt-get install curl"
    echo "  or:   sudo apt-get install wget"
    exit 1
fi
$KEY_CMD
if [ $? -ne 0 ]; then
    echo "ERROR: Failed to install drivestrike repository key ($?)"
    exit 1
fi

# Add the DriveStrike repository
url_port=""
if [[ -f /usr/bin/lsb_release ]]; then
  /usr/bin/lsb_release -d | grep -q 14\.04
  if [[ $? == 0 ]]; then
    url_port=":444"
  fi
fi
echo deb [arch=$ARCH] https://app.drivestrike.com$url_port/static/apt/ stretch main > /etc/apt/sources.list.d/drivestrike.list

# Install DriveStrike
apt-get update && apt-get install -y drivestrike

# Register DriveStrike and start the DriveStrike service
if [[ -f /usr/sbin/drivestrikerun.sh ]]; then
    /usr/sbin/drivestrikerun.sh
else
    /usr/bin/drivestrikerun.sh
fi
