#!/bin/bash
# AWSに直接コピペすると文字化けするので注意

# hostname of main server
BM_DOMAIN=vr.binaural.me
hostname=relay.${BM_DOMAIN}

# function to get hostname of main server. 
function getHostname() {
    ipaddr=
    while [ "$ipaddr" = "" ]; do
        ipaddr=`host -ta ${hostname}`
        ipaddr=${ipaddr##* }
        if [ "$ipaddr" = "`curl 169.254.169.254/latest/meta-data/public-ipv4`" ]; then break; fi
        #if [ "$ipaddr" = "13.230.218.86" ]; then break; fi
        ipaddr=
        sleep 3s;
    done
}

sudo apt-get -y update
#sudo apt-get -y install emacs
sudo apt-get -y install git
sudo apt-get -y install unzip
curl -fsSL https://deno.land/x/install/install.sh | sh

sudo apt-get -y install nginx

getHostname
if [ "`curl -LI https://binaural.me/public_packages/uploader/vr/${hostname}_fullchain.pem -o /dev/null -w '%{http_code}\n' -s`" = "200" ]; then
    sudo mkdir -p /etc/letsencrypt/live/${hostname}
    sudo curl --output /etc/letsencrypt/live/${hostname}/fullchain.pem https://binaural.me/public_packages/uploader/vr/${hostname}_fullchain.pem
    sudo curl --output /etc/letsencrypt/live/${hostname}/privkey.pem https://binaural.me/public_packages/uploader/vr/${hostname}_privkey.pem
else
    # get cert by certbot
    sudo snap install core; sudo snap refresh core
    sudo apt-get remove certbot
    sudo snap install --classic certbot
    sudo ln -s /snap/bin/certbot /usr/bin/certbot
    sudo certbot --nginx --non-interactive --agree-tos --email hasevr@gs.haselab.net --domains $hostname

    #upload cert 
    sudo curl -X POST -H "Content-Type: multipart/form-data" -F "do_upload=true" -F "userfile=@/etc/letsencrypt/live/${hostname}/fullchain.pem;filename=${hostname}_fullchain.pem" https://binaural.me/public_packages/uploader/vr/index.php 
    sudo curl -X POST -H "Content-Type: multipart/form-data" -F "do_upload=true" -F "userfile=@/etc/letsencrypt/live/${hostname}/privkey.pem;filename=${hostname}_privkey.pem" https://binaural.me/public_packages/uploader/vr/index.php 
fi

#Install and start bmRelayServer
cd
git clone https://github.com/BinauralMeet/bmRelayServer
cd bmRelayServer
ln -s /etc/letsencrypt/live/${hostname}/fullchain.pem host.crt
ln -s /etc/letsencrypt/live/${hostname}/privkey.pem host.key
/root/.deno/bin/deno run --allow-net --allow-read bmRelayServer.ts 443 TLS>bmRelayServer.log
