#!/bin/bash

# setup server

## PREFLIGHT

ORIGIN_PWD="$PWD"

if ! [ "$(id -u)" = "0" ]; then
    echo "please perform as root, attempting to escalate privileges..."
    exec sudo $(cat /proc/$$/cmdline | sed 's/\x00/ /g')
    exit 1
fi

echo "testing git connection..."
if ! ssh git@git.ixvd.net &>/tmp/$$-ssh-output; then
    echo "can't connect to git, please setup ssh (logs: /tmp/$$-ssh-output)"
    exit 1
fi
rm /tmp/$$-ssh-output

## MAIN

set -e

for s in tools/server-setup.d/*; do
    echo "running $s..."
    $s | while read line; do
    echo "$s: $line"
    done
done

if [ -d "servers/$HOSTNAME/setup.d" ]; then
    echo "running server specific setup scripts..."
    cd servers/$HOSTNAME
    for s in setup.d/*; do
        echo "running (servers/$HOSTNAME/)$s..."
        $s | while read line; do
            echo "$s: $line"
        done
    done
    cd -
fi