#!/bin/bash

# Setup user and install wgas app as service

set -x

export APP_REPO=https://github.com/lalanza808/wgas
export APP_USER=wgas
export APP_SVC=wgas
export APP_HOME=/opt/wgas
export SYSTEMD_PATH=/lib/systemd/system/wgas.service

# These need to be passed in from the cloud-init or provider data
export WGAS_PUBKEY=$WGAS_PUBKEY
export WGAS_ENDPOINT=$WGAS_ENDPOINT
export WGAS_SUDO=true
export WGAS_DNS=$WGAS_DNS
export WGAS_ROUTE=$WGAS_ROUTE
export WGAS_PORT=$WGAS_PORT

# Create app user and directory
useradd $APP_USER -s /sbin/nologin -M
mkdir -p $APP_HOME
chown -R ubuntu:ubuntu $APP_HOME

# Install Rust and build application
cat << EOF > /opt/install_app.sh
#!/bin/bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | RUSTUP_HOME=~/.rustup sh -s -- -y
source ~/.cargo/env
git clone $APP_REPO $APP_HOME
cd $APP_HOME
rustup override set nightly
cargo build --release
EOF
chmod +x /opt/install_app.sh
sudo -u ubuntu -E /opt/install_app.sh

# Add app user to sudoers file
echo "$APP_USER ALL=(ALL) NOPASSWD: $(which wg), $(which wg-quick)" >> /etc/sudoers

# Setup systemd service
cat $APP_HOME/util/wgas.service | envsubst > $SYSTEMD_PATH
chmod 755 $SYSTEMD_PATH
systemctl daemon-reload
systemctl enable $APP_SVC
systemctl start $APP_SVC
