#!/bin/bash
#
# vhost-stack
# https://git.stack-source.com/msb/vhost-stack
# MIT License Copyright (c) 2021 Matthew Saunders Brown

# load include file
source $(dirname $0)/vhost.sh

help()
{
  thisfilename=$(basename -- "$0")
  echo "Makes sure all existing varnish configs are loaded."
  echo ""
  echo "usage: $thisfilename [-h]"
  echo ""
  echo "  -h    Print this help."
  echo ""
  echo "        The varnish config is broken down in to individual"
  echo "        configurations for each virtualhost. Each config has"
  echo "        to be included by the master sites.vcl. This tool makes"
  echo "        sure all existing virtualhost varnish configs are"
  echo "        properly included in sites.vcl, and removes includes"
  echo "        for varnish virtualhost configs that have been deleted."
  exit
}

# check for -h
if [ -n "$1" ]; then
  if [ $1 == "-h" ]; then
    help
    exit
  fi
fi

if [ ! -f /etc/varnish/sites.d/example.com.vcl ]; then

  echo "ERROR: example.vlc does not exist"
  exit 1

fi

sitesArray=(`ls -1 /etc/varnish/sites.d/`)
truncate -s 0 /etc/varnish/sites.vcl

for site in "${sitesArray[@]}"
do

  echo include \"sites.d/$site\"\; >> /etc/varnish/sites.vcl

done

exit 0