#!/bin/bash
SCRIPT_DIR=$(dirname "$0")

# default config should always work for localhost

function die() {
    echo "$1"
    exit 1
}

function dashes() {
    for ((i=0; i<$1; i++)); do
        echo -n "-"
    done
    echo ""
}

function centerprint() {
    # print $1 centered
    local width=$2
    local padding=$(( (width - ${#1}) / 2 ))    
    for ((i=0; i<$padding; i++)); do
        echo -n " "
    done

    echo "$1"
}

function title() {
    # determine terminal width    
    TERMINAL_WIDTH=$(tput cols)

    echo " "
    dashes $TERMINAL_WIDTH
    centerprint "$1" $TERMINAL_WIDTH
    dashes $TERMINAL_WIDTH
}

# do we have the first argument?
if [ -z "$1" ]; then
    echo "Usage: $0 <template>"
    exit 1
fi

TEMPLATE=$(basename "$1")

if [ ! -d "$SCRIPT_DIR/$TEMPLATE" ]; then
    echo "Local Template $TEMPLATE does not exist"
    exit 1
fi

# for now, we need to build and locally install to test the template. Check if it's up to date.

title "Checking template $TEMPLATE"

SERVICE_NAME="test-$TEMPLATE"

title "Nuking old service"
ds fullnuke localhost $SERVICE_NAME || die "Failed to fullnuke old service"

title "Creating service"
ds create-service localhost $TEMPLATE $SERVICE_NAME || die "Failed to create service"

title "Installing service"
ds install localhost $SERVICE_NAME || die "Failed to install service"

title "Stopping service"
ds stop localhost $SERVICE_NAME || die "Failed to stop service"

title "Starting service"
ds start localhost $SERVICE_NAME || die "Failed to start service"

title "Listing services"
ds list localhost || die "Failed to list services"

title "Backing up service"
ds backup localhost $SERVICE_NAME || die "Failed to backup service"

title "Restoring service"
ds restore localhost $SERVICE_NAME latest || die "Failed to restore service"

title "Checking status"
ds status localhost $SERVICE_NAME || die "Failed to check status"

title "Nuking service"
ds nuke localhost $SERVICE_NAME || die "Failed to nuke service"

title "Listing services"
ds list localhost || die "Failed to list services"


# change to green font
echo -e "\033[32m"
title "ALL TESTS PASSED FOR $TEMPLATE"
echo -e "\033[0m"
echo " "