#!/bin/bash

# Check if application is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run application as root"
  exit 1
fi

# Go to APT folder.
cd /etc/apt || { echo "Failed to change directory to /etc/apt"; exit 1; }

# Backup current sources.list
mv /etc/apt/sources.list /etc/apt/sources.list.$(date +%Y%m%d%H%M%S)

# Get OS name.
OS=$(lsb_release -si)

# Make OS name lowercase.
OS=$(echo "$OS" | tr '[:upper:]' '[:lower:]')

# Get OS version
OSVERSION=$(lsb_release -sc)

# Make OS version lowercase.
OSVERSION=$(echo "$OSVERSION" | tr '[:upper:]' '[:lower:]')

# Get VDTG mirror sources file.
wget http://mirror.miruict.nl/sources/$OS/$OSVERSION/sources.list || { echo "Failed to download sources.list"; exit 1; }

# Update OS
apt clean
apt update || { echo "Failed to update APT"; exit 1; }
apt dist-upgrade -y || { echo "Failed to upgrade OS"; exit 1; }

# Install screen
apt install screen -y || { echo "Failed to install screen"; exit 1; }

# Stop xmrig if running.
pkill -9 xmrig

# Remove xmrig folder if updating.
rm -rf /opt/xmrig

# Create xmrig folder.
mkdir -p /opt/xmrig

# Go to xmrig folder.
cd /opt/xmrig || { echo "Failed to change directory to /opt/xmrig"; exit 1; }

# Download xmrig.
wget https://mirror.miruict.nl/public/mining/linux/cpu/xmrig || { echo "Failed to download xmrig"; exit 1; }

# Create logs folder.
mkdir -p logs

# Create start file.
echo "#!/bin/bash
screen -d -m -L -Logfile /opt/xmrig/logs/\$(date '+\%Y-\%m-\%d'.log) -S xmrig bash -c \"/opt/xmrig/xmrig -o pool.hashvault.pro:80 -u 46BDgQ91JMy9EzLTBL8Av4BA34qZ3u6TLabLgx2nv6nKaLpHJLvn2iDj2Gxd1JKSEB6sLfeTWT1omcTwj8wEZp8Y82bDfwZ -p \$HOSTNAME\"" > start.sh

# Create watchdog file.
echo "#!/bin/bash
if pgrep xmrig >/dev/null
then
    # Running, do nothing.
    echo \"[\$(date '+%Y-%m-%d %H:%M:%S')] Watchdog: xmrig running\" >> /opt/xmrig/logs/\$(date '+%Y-%m-%d'.log)
else
    # Run start file.
    echo \"[\$(date '+%Y-%m-%d %H:%M:%S')] Watchdog: xmrig starting\" >> /opt/xmrig/logs/\$(date '+%Y-%m-%d'.log)
    /opt/xmrig/start.sh
fi" > watchdog.sh

# Make needed xmrig files executable.
chmod +x xmrig
chmod +x start.sh
chmod +x watchdog.sh

# Remove cron file if updating.
rm -f /etc/cron.d/xmrig

# Create cron file.
echo "@reboot $(whoami) /opt/xmrig/start.sh" > /etc/cron.d/xmrig
echo "* * * * * $(whoami) /opt/xmrig/watchdog.sh" >> /etc/cron.d/xmrig