#!/bin/bash
source ./variables

echo "Installing dependencides... Please stay for a second, you will confirm the install"
apt update
apt install sudo wireguard-tools


echo "Setting up user..."
useradd -m -s /bin/bash $USERNAME


echo "Configuring WireGuard..."
WG_SUBNET="fc$(openssl rand -hex 1):$(openssl rand -hex 2):$(openssl rand -hex 2):$(openssl rand -hex 2)"
WG_LISTEN_PORT=$(shuf -i 49152-65535 -n 1)
WG_LOCAL_PRIVKEY=$(wg genkey)
WG_LOCAL_PUBKEY=$(echo $WG_LOCAL_PRIVKEY | wg pubkey)

cat <<EOF > /etc/wireguard/vmh-ssh-vpn.conf
[Interface]
ListenPort = $WG_LISTEN_PORT
PrivateKey = $WG_LOCAL_PRIVKEY
Address = $WG_SUBNET::1/64

[Peer]
PublicKey = $WIREGUARD_PUBKEY
AllowedIPs = $WG_SUBNET::2/128
EOF

systemctl enable --now wg-quick@vmh-ssh-vpn


echo "Configuring ssh..."
mkdir /home/$USERNAME/.ssh
echo $MY_SSH_KEY > /home/$USERNAME/.ssh/authorized_keys

cat <<EOF > /etc/ssh/sshd_config.d/10-vmh_ssh.conf
X11Forwarding no
PasswordAuthentication no
PubkeyAuthentication yes
PermitRootLogin no

ListenAddress $WG_SUBNET::1
EOF

mkdir /etc/systemd/system/sshd.service.d
cat <<EOF > /etc/systemd/system/sshd.service.d/10-vmh-listen.conf
[Unit]
After=wg-quick@vmh-ssh-vpn.service
EOF

systemctl restart sshd


echo "Configuring sudo..."
cat <<EOF > /etc/sudoers.d/99-vmh-newuser
$USERNAME    ALL=(ALL:ALL)   NOPASSWD:ALL
EOF

echo
echo "BEFORE DISCONNECTING, FOLLOW THE FOLLOWING STEPS"
echo "You won't be able to reconnect if you don't."
echo
echo "1. Install the WireGuard config (fill in the gaps)"
echo
echo "[Interface]"
echo "PrivateKey = ..."
echo "Address = $WG_SUBNET::2/64"
echo "[Peer]"
echo "Endpoint = ...:$WG_LISTEN_PORT"
echo "PublicKey = $WG_LOCAL_PUBKEY"
echo "AllowedIPs = $WG_SUBNET::1/128"
echo
echo "2. Use this command to connect"
echo
echo "ssh $USERNAME@$WG_SUBNET::1"