#!/bin/bash

# Generate opening text.
cat <<EOF

* * * * *

Welcome!

The script will install hero and set the environment to work with mdbook.
This will take a couple of minutes.

* * * * *

EOF

sleep 2

# Disable "Pending kernel upgrade" and  "Daemons using outdated libraries" windows
sed -i "s/#\$nrconf{kernelhints} = -1;/\$nrconf{kernelhints} = -1;/g" /etc/needrestart/needrestart.conf
sed -i "/#\$nrconf{restart} = 'i';/s/.*/\$nrconf{restart} = 'a';/" /etc/needrestart/needrestart.conf

# Update and install dependencies
apt-get update
apt-get install -y lsb-release gpg
curl https://sh.rustup.rs -sSf | sh -s -- -y
source "$HOME/.cargo/env"
export PATH=$PATH:/root/.cargo/bin
curl -fsSL https://packages.redis.io/gpg | gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | tee /etc/apt/sources.list.d/redis.list
apt-get update
apt-get install -y redis pkg-config gcc libssl-dev

# Download and run the hero installer script
curl https://raw.githubusercontent.com/freeflowuniverse/crystallib/development/scripts/installer_hero.sh > /tmp/hero_install.sh
bash /tmp/hero_install.sh

# Start the SSH agent, run hero mdbook and build the mdbook
eval $(ssh-agent)
hero mdbook -u https://git.ourworld.tf/tfgrid/info_tfgrid/src/branch/main/heroscript
cd /root/hero/var/mdbuild/duniayetu
mdbook build

# Generate closing text after successful script.
cat <<EOF

* * * * *

The script has been successfully completed.

To see the mdbook live on your browser, 
run the following command with the proper port (here we use 3333).

mdbook serve --hostname 0.0.0.0 --port 3333

Happy mdbooking!

* * * * *

EOF

# Send stderr to null and exit gracefully
return 2> /dev/null; exit