#!/bin/bash

INSTALL_DIR=~/.local/opt/autodarts

if [[ $1 == "--uninstall" || $1 == "--purge" ]]; then
  echo "Trying to remove autodarts"
  sudo systemctl stop autodarts
  sudo systemctl disable autodarts
  sudo rm /etc/systemd/system/autodarts.service
  sudo rm /etc/systemd/system/autodartsupdater.service
  rm -rf ${INSTALL_DIR}
  rm -f ~/.local/bin/autodarts
  rm -f ~/.local/bin/updater.sh

  if [[ $1 == "--purge" ]]; then
    echo "Purging all autodarts files and configurations"
    rm -rf ~/.config/autodarts
  fi

  echo "Reloading systemd daemon"
  sudo systemctl daemon-reload

  echo "Autodarts uninstalled"

  exit
fi

AUTOSTART="true"
AUTOUPDATE="true"
while getopts "nu" OPTION; do
  case "${OPTION}" in
    n)
      AUTOSTART="false"
      ;;
    u)
      AUTOUPDATE="false"
      ;;
    *)
      AUTOSTART="true"
      AUTOUPDATE="true"
      ;;
  esac
done

shift "$(($OPTIND -1))"

PLATFORM=$(uname)
if [[ "$PLATFORM" = "Linux" ]]; then
  PLATFORM="linux"
else
  echo "Platform is not 'linux', and hence is not supported by this script." && exit 1
fi

ARCH=$(uname -m)
case "${ARCH}" in
  "x86_64"|"amd64") ARCH="amd64";;
  "aarch64"|"arm64") ARCH="arm64";;
  "armv7l") ARCH="armv7l";;
  *) echo "Kernel architecture '${ARCH}' is not supported." && exit 1;;
esac

CHANNEL=latest
REQ_VERSION=$1
REQ_VERSION="${REQ_VERSION#v}"
if [[ "$REQ_VERSION" = "" ]]; then
  VERSION=$(curl -sL https://get.autodarts.io/detection/latest/${PLATFORM}/${ARCH}/RELEASES.json | grep -o '"currentVersion":"v[0-9]\+\.[0-9]\+\.[0-9]\+"' | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+')
  echo "Installing latest version v${VERSION}."
elif [[ "$REQ_VERSION" = "beta" ]]; then
  CHANNEL=beta
  VERSION=$(curl -sL https://get.autodarts.io/detection/${CHANNEL}/${PLATFORM}/${ARCH}/RELEASES.json | grep -o '"currentVersion":"v[0-9]\+\.[0-9]\+\.[0-9]\+-beta\.[0-9]\+"' | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+-beta\.[0-9]\+')
  echo "Installing latest beta version v${VERSION}."
# elif [[ "$REQ_VERSION" = "alpha" ]]; then
#   CHANNEL=alpha
#   VERSION=$(curl -sL https://get.autodarts.io/detection/${CHANNEL}/${PLATFORM}/${ARCH}/RELEASES.json | grep -o '"currentVersion":"v[0-9]\+\.[0-9]\+\.[0-9]\+-alpha\.[0-9]\+"' | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+-alpha\.[0-9]\+')
#   echo "Installing latest alpha version v${VERSION}."
else
  if [[ "$REQ_VERSION" == *"beta"* ]]; then
    CHANNEL=beta
    VERSION=$(curl -sL https://get.autodarts.io/detection/${CHANNEL}/${PLATFORM}/${ARCH}/RELEASES.json | grep -o "\"version\":\"v${REQ_VERSION}\"" | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+-beta\.[0-9]\+')
  # elif [[ "$REQ_VERSION" == *"alpha"* ]]; then
  #   CHANNEL=alpha
  #   VERSION=$(curl -sL https://get.autodarts.io/detection/${CHANNEL}/${PLATFORM}/${ARCH}/RELEASES.json | grep -o "\"version\":\"v${REQ_VERSION}\"" | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+-alpha\.[0-9]\+')
  else
    VERSION=$(curl -sL https://get.autodarts.io/detection/latest/${PLATFORM}/${ARCH}/RELEASES.json | grep -o "\"version\":\"v${REQ_VERSION}\"" | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+')
  fi
  echo "Checking channel '${CHANNEL}' for requested version v${REQ_VERSION}."
  if [[ "$VERSION" = "" ]]; then
    echo "Requested version v${REQ_VERSION} not found." && exit 1
  fi
  echo "Installing requested version v${VERSION}."
fi

# Clean up old install location
rm -f ~/.local/bin/autodarts
rm -f ~/.local/bin/updater.sh

# Download autodarts and unpack to install directory
mkdir -p ${INSTALL_DIR}
echo "Downloading and extracting 'autodarts${VERSION}.${PLATFORM}-${ARCH}.tar.gz' into '${INSTALL_DIR}'."
curl -sL https://get.autodarts.io/detection/${CHANNEL}/${PLATFORM}/${ARCH}/autodarts${VERSION}.${PLATFORM}-${ARCH}.tar.gz | tar -xz -C ${INSTALL_DIR}
echo "Making ${INSTALL_DIR}/autodarts executable."
chmod +x ${INSTALL_DIR}/autodarts
mkdir -p ~/.local/bin
ln -sf ${INSTALL_DIR}/autodarts ~/.local/bin/autodarts
curl -sL https://get.autodarts.io/sh/update_autodarts_headless.sh > ${INSTALL_DIR}/updater.sh
sed -i "s/^CHANNEL=.*/CHANNEL=${CHANNEL}/" ${INSTALL_DIR}/updater.sh
chmod +x ${INSTALL_DIR}/updater.sh

if [[ ${AUTOUPDATE} = "true" && "$PLATFORM" = "linux" ]]; then
  # Create systemd service
  echo "Creating systemd service for autodarts auto updater to run on system startup."
  echo "We will need sudo access to do that."

  if [[ ${USER} = "root" ]]; then
    cat <<EOF | sudo tee /etc/systemd/system/autodartsupdater.service >/dev/null
# autodartsupdater.service
[Unit]
Description=Autodarts automatic updater.
Wants=network-online.target
After=network.target network-online.target

[Service]
Type=simple
User=root
ExecStart=/root/.local/opt/autodarts/updater.sh

[Install]
WantedBy=multi-user.target
EOF
  else
    cat <<EOF | sudo tee /etc/systemd/system/autodartsupdater.service >/dev/null
# autodartsupdater.service
[Unit]
Description=Autodarts automatic updater.
Wants=network-online.target
After=network.target network-online.target

[Service]
Type=simple
User=${USER}
ExecStart=/home/${USER}/.local/opt/autodarts/updater.sh

[Install]
WantedBy=multi-user.target
EOF
  fi
    echo "Enabling systemd service for automatic updates."
    sudo systemctl enable autodartsupdater
fi

if [[ ${AUTOSTART} = "true" && "$PLATFORM" = "linux" ]]; then
    # Create systemd service
    echo "Creating systemd service for autodarts to start on system startup."
    echo "We will need sudo access to do that."

    if [[ ${USER} = "root" ]]; then
      cat <<EOF | sudo tee /etc/systemd/system/autodarts.service >/dev/null
# autodarts.service

[Unit]
Description=Start/Stop Autodarts board service
Wants=network-online.target
After=network.target network-online.target

[Service]
User=root
ExecStart=/root/.local/opt/autodarts/autodarts
Restart=on-failure
KillSignal=SIGINT
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF
  else
    cat <<EOF | sudo tee /etc/systemd/system/autodarts.service >/dev/null
# autodarts.service

[Unit]
Description=Start/Stop Autodarts board service
Wants=network-online.target
After=network.target network-online.target

[Service]
User=${USER}
ExecStart=/home/${USER}/.local/opt/autodarts/autodarts
Restart=on-failure
KillSignal=SIGINT
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF
  fi

  echo "Adding the current user to the group video"
  sudo adduser ${USER} video

  echo "Enabling systemd service."
  sudo systemctl enable autodarts

  echo "Starting autodarts."
  sudo systemctl stop autodarts
  sudo systemctl start autodarts
fi

echo "Done."
