#!/bin/bash

. sbs/exec/config/allg

. $certbasedir/config/functions
. $(dirname $BASH_SOURCE)/config/functions

httpfile=$(findtemplate apache site_http.conf)
httpsfile=$(findtemplate apache site_https.conf)

if [ "$varenewcertInput" != "0" ]; then check_capasswd "$vapasswd"; fi
if [ "$vadocumentrootInput" = "" ]; then vadocumentrootInput="$vadomainInput"; fi

certname="$vanameInput"
if [ "$vanameInput" = "000-default-ssl" ] || [ "$vanameInput" = "000-default" ]; then
    vadomainInput="$(hostname)";
    certname="$(hostname)";
    vaenabledInput="1";
    vanameInput="$vanameInput_old";

    mne_need_error
    systemctl is-enabled samba-ad-dc.service >/dev/null 2>/dev/null
    if [ "$?" = "0" ]; then
       domain=$(samba-tool domain info 127.0.0.1 | awk -v FS=: '/Domain/ { sub(/^[ \t]+/, "", $2); print $2 }')
       vaaliasesInput="$(hostname).$domain $domain"
    else
       vaaliasesInput=
    fi
fi

if [ "$vanameInput" = "" ];  then vanameInput="mne_$vadomainInput";     fi

if [ ${vadocumentrootInput:0:1} != "/" ]; then vadocumentrootInput="$apachedatalocation/$vadocumentrootInput"; fi

file="$apacherootdir/sites-available/$vanameInput_old.conf"
documentroot=$(awk '/^[ \t]*#/ { next } tolower($1) ~ /documentroot/ { print $2; exit; }' "$file")

if [ "$documentroot" != "" ] && [ "$documentroot" != "$vadocumentrootInput" ]; then
    mkdir -p "$vadocumentrootInput";
    ( cd "$documentroot"; tar -cf - . ) | ( cd "$vadocumentrootInput"; tar -xf - )
    savefile "$documentroot"
fi

conffile=$httpsfile
if [ "$vahttpsonlyInput" != "1" ]; then conffile="\"$conffile\" \"$httpfile\""; fi

if [ "$vaconfInput" = "" ]; then
  vaconfInput="$(eval "cat $conffile")"
else
  vaconfInput="$(echo "$vaconfInput" | sed -e 's/\\n/\n/g')"
  savefile "$apacherootdir/sites-available/$4.conf"
fi

port=$(get_port)
sport=$(get_sport)

site_writeconf "$vaconfInput" "$port" "$sport" "$vanameInput" "$vadomainInput" "$vaaliasesInput" "$vaemailInput" "$vadocumentrootInput" "$datadir" "$certname"


if [ "$varenewcertInput" != "0" ]; then
  name="$vanameInput"
  if [ "$vanameInput" = "000-default-ssl" ] || [ "$vanameInput" = "000-default" ]; then
    name="$(hostname)"
  fi

  cert_mkkey "$name"
  cert_mkcsr "$name" "$vadomainInput" "$vaaliasesInput"
  cert_mkcrt "$name" "$vapasswd"
fi

if [ "$vaenabledInput" != "" ] && [ "$vaenabledInput" != "0" ]; then
    a2ensite "$vanameInput" >&$logfile 2>&$logfile 
    mne_need_error
    err="$(apachectl configtest  2>/dev/null >/dev/null; exit $? )"
    if [ "$?" != "0" ]; then
       echo "$err" >&2
       a2dissite "$vanameInput"
       $apachereload >&$logfile 2>&$logfile 
       exit 1
    fi
else
    a2dissite "$vanameInput" >&$logfile 2>&$logfile  
fi

$apachereload >&$logfile 2>&$logfile
