#!/bin/bash

echo "Welcome to the Discord-Linux CodeServer Automated installer"
echo "This installer will automatically select a port on your container."
echo "I will let you know how to access your installation when installation is complete."
echo ""


echo "downloading the Notification Bot"
wget -q -O /usr/bin/notif https://ssh.surf/notify-x64 && chmod +x /usr/bin/notif
echo "Done"

notif "Welcome to the Code-Server Automated installer for Discord-Linux x64, We are preparing your installation..."

apt update
DEBIAN_FRONTEND=noninteractive apt upgrade -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold"  -y

wget -q https://github.com/coder/code-server/releases/download/v3.12.0/code-server_3.12.0_amd64.deb

notif "Installing Code-Server 3.12 using DPKG"

dpkg -i code-server_3.12.0_amd64.deb

rm -f code-server_3.12.0_amd64.deb

notif "Downloading our configurations"

wget -q -O /var/tools/startCodeServer.json https://ssh.surf/install/code-server/startCodeServer.json

wget -q -O /var/tools/startCodeServer.sh https://ssh.surf/install/code-server/startCodeServer.sh

chmod +x /var/tools/startCodeServer.sh

mkdir -vp /root/.config/code-server/

wget -q -O /root/.config/code-server/config.yaml https://ssh.surf/install/code-server/config.yaml

PASS=$(openssl rand -hex 12)


sed -i "s/replaceme/${PASS}/g" ~/.config/code-server/config.yaml

sed -i "s/#code-server/pm2 start \/var\/tools\/startCodeServer.json \&\& relayPort 8080/g" /start.sh

pm2 start /var/tools/startCodeServer.sh


sleep 5
notif "Sleeping for 5 seconds to allow for code-server to start...."

relayPort 8080

sleep 5
notif "Sleeping to allow the relay to start..."

url=$(grep -hPo "(?<=listening ).*" /root/.pm2/logs/Relay-8080-out.log  | head -n 1 | sed 's/$/.virt.fun/')

notif "The installation has completed. You may access your install at: https://$url with the password $PASS"
