#!/usr/bin/env bash

set -e

GO_IPFS_VERSION=v0.4.6

BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Download and install IPFS
mkdir "$BASE_DIR/tmp"
wget "https://dist.ipfs.io/go-ipfs/${GO_IPFS_VERSION}/go-ipfs_${GO_IPFS_VERSION}_linux-arm.tar.gz" -O "$BASE_DIR/tmp/go-ipfs.tar.gz"
tar xvfz "$BASE_DIR/tmp/go-ipfs.tar.gz" -C "$BASE_DIR/tmp"
sudo cp "$BASE_DIR/tmp/go-ipfs/ipfs" /usr/local/bin/ipfs
sudo chown root:staff /usr/local/bin/ipfs
rm -rf "$BASE_DIR/tmp"

# Initialize IPFS
ipfs init

# Configure systemd to start ipfs.service on system boot
sudo cp "$BASE_DIR/ipfs.service" /lib/systemd/system/ipfs.service
sudo sed -i "s|USER_HOME|${HOME}|" /lib/systemd/system/ipfs.service
sudo systemctl daemon-reload
sudo systemctl enable ipfs.service
sudo systemctl start ipfs.service

# Install nginx
sudo apt-get install nginx -y

# Configure HTTP to IPFS gateway
sudo cp "$BASE_DIR/ipfs-http-gateway.nginx" /etc/nginx/sites-available/ipfs-http-gateway
sudo ln -s /etc/nginx/sites-available/ipfs-http-gateway /etc/nginx/sites-enabled/ipfs-http-gateway
sudo rm /etc/nginx/sites-enabled/default
sudo systemctl restart nginx.service
