#!/bin/bash

if [ "$EUID" -ne 0 ]; then
  echo "This script must be run as root"
  exit
fi

set -e

URL="https://github.com/idlesauce/PS5-Exploit-Host-Self-Host-Tool/releases/latest/download"
EXECUTABLE_NAME="PS5-Exploit-Host-Self-Host-Tool"
DL_FILENAME="PS5-Exploit-Host-Self-Host-Tool"
DEST_DIR="/usr/local/bin"
SERVICE_NAME="PS5-Exploit-Host-Self-Host-Tool"
RUN_THOUGH_DOTNET=false

AP_FLAG=""
if [ "$1" == "ap" ]; then
  AP_FLAG="--default-config-wifi-ap"
fi

ARCH=$(uname -m)
case "$ARCH" in
  "x86_64")
    DL_FILENAME="${DL_FILENAME}-linux-x64"
    EXECUTABLE_NAME=$DL_FILENAME
    ;;
  "aarch64")
    DL_FILENAME="${DL_FILENAME}-linux-arm64"
    EXECUTABLE_NAME=$DL_FILENAME
    ;;
  *)
    echo "Currently this script only supports x86_64 and aarch64 architectures. Your architecture is $ARCH"
    exit 1
    ;;
esac

echo "Installing dependencies..."

apt-get update
apt-get install -y curl dnsmasq hostapd iw wireless-tools iptables unzip psmisc

echo "Installed dependencies"
echo "Disabling hostapd and dnsmasq services..."

systemctl disable hostapd dnsmasq

echo "Disabled hostapd and dnsmasq services"
echo "Stopping hostapd and dnsmasq services..."

systemctl stop hostapd dnsmasq

echo "Stopped hostapd and dnsmasq services"
echo "Downloading $DL_FILENAME from $URL to $DEST_DIR..."

# Stop the service in case we are updating
systemctl stop $SERVICE_NAME || true

URL="${URL}/${DL_FILENAME}"
mkdir -p $DEST_DIR
curl -L $URL -o $DEST_DIR/$EXECUTABLE_NAME

echo "Downloaded $EXECUTABLE_NAME to $DEST_DIR"
echo "Setting permissions on executable..."

chmod +x $DEST_DIR/$EXECUTABLE_NAME

echo "Set permissions on executable"
echo "Upping inotify watches..."

echo fs.inotify.max_user_watches=65536 | tee -a /etc/sysctl.conf && sysctl -p

echo "Upped inotify watches"
echo "Creating $SERVICE_NAME service..."

EXEC_START="$DEST_DIR/$EXECUTABLE_NAME"

cat <<EOF > /etc/systemd/system/$SERVICE_NAME.service
[Unit]
Description=PS5 Exploit Host Self Host Tool
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
ExecStart=$EXEC_START --default-config-continue $AP_FLAG
Restart=on-failure
User=root

[Install]
WantedBy=multi-user.target
EOF

echo "Created $SERVICE_NAME service"
echo "Reloading systemd daemon..."

systemctl daemon-reload

echo "Reloaded systemd daemon"
echo "Enabling $SERVICE_NAME service..."

systemctl enable $SERVICE_NAME

echo "Enabled $SERVICE_NAME service"
echo "Starting $SERVICE_NAME service..."

systemctl start $SERVICE_NAME

echo ""
echo "All done! You can configure the service by editing /root/.ps5-exploit-host/config.ini then restart the service with 'sudo systemctl restart $SERVICE_NAME'"
if [ "$1" == "ap" ]; then
    DEFAULT_WIFI_AP_PASSWORD=$(grep -oP 'WifiAPPassword=\K.*' /root/.ps5-exploit-host/config.ini)
  echo "Default Wifi AP Password is: $DEFAULT_WIFI_AP_PASSWORD"
fi
DEFAULT_TARGETIP=$(grep -oP 'TargetIP=\K.*' /root/.ps5-exploit-host/config.ini)
echo "Default Target IP is: $DEFAULT_TARGETIP"