#!/bin/bash
clear='\033[0m'
green='\033[1;32m'
cyan='\033[1;36m'
yellow='\033[0;33m'
grey='\033[0;37m'

  echo -e "${green}           __          __   _            __ "
  echo -e "          / /   ____  / /__(_)___  ___  / /_"
  echo -e "         / /   / __ \/ //_/ / __ \/ _ \/ __/ "
  echo -e "        / /___/ /_/ / ,< / / / / /  __/ /_"
  echo -e "       /_____/\____/_/|_/_/_/ /_/\___/\__/ "
  echo -e "${yellow}Pi-Apps Installer by Minotaurware.net${grey}_______________  "
  echo -e "|___|___|___|___|___|___|___|___|___|___|___|___|___| "
  echo -e "|_|___|___|___|___|___|___|___|___|___|___|___|___|_| "
  echo -e "${clear}"

echo "Installing public key and adding packages..."
sudo modprobe tun || exit 1
sudo wget -qO /etc/apt/trusted.gpg.d/oxen.gpg https://deb.oxen.io/pub.gpg || error "Failed to download /etc/apt/trusted.gpg.d/oxen.gpg"
echo "deb https://deb.oxen.io $(get_codename) main" | sudo tee /etc/apt/sources.list.d/oxen.list
echo "Installing Lokinet-GUI and resolvconf..."
install_packages lokinet-gui resolvconf || exit 1
if [ ! -e /etc/systemd/system/lokinet.service.d/override.conf ]; then
  echo "Applying systemd tun override..."
  sudo mkdir /etc/systemd/system/lokinet.service.d
  echo '[Service]' | sudo tee -a /etc/systemd/system/lokinet.service.d/override.conf >/dev/null
  echo 'ExecStartPre=+modprobe tun' | sudo tee -a /etc/systemd/system/lokinet.service.d/override.conf >/dev/null
  sudo systemctl daemon-reload
fi

echo "Updating resolvconf and starting lokinet service..."
sudo resolvconf -u
sudo sed '/upstream/s/^#//' -i /etc/loki/lokinet.ini || error "Failed to set upstream resolver"
sudo systemctl restart lokinet
if [ $? != 0 ];then
  warning "The lokinet service failed to restart. Output of journalctl -u lokinet"
  sudo journalctl -u lokinet | sed 's/^/> /g'
  error "Systemd failed to restart the lokinet service!"
fi
 
echo "Installation complete!"
