#!/bin/bash -x
#
# Federated installation script

PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
. /federated/lib/functions.sh
. /federated/lib/network.sh
trap cleanup `seq 1 15`

get_config() {
#  FSTACKURL="http://137.184.95.3:8000"
#  [ ! -d "/federated/lib" ] && mkdir -p /federated/lib

  # Download each library file
#  for i in checks network dns ldap mail; do
#    if [ ! -f "/federated/lib/$i.sh" ]; then
#      curl $FSTACKURL/$i.sh -o /federated/lib/$i.sh -s -f &> /dev/null
#      [ $? -ne 0 ] && failcheck "Couldn't download $i.sh"
#    fi
#  done

  COUNTRIES=("AF" "AL" "DZ" "AS" "AD" "AO" "AI" "AQ" "AG" "AR" "AM" "AW" "AU" "AT" "AZ" "BS" "BH" "BD" "BB" "BY" "BE" "BZ" "BJ" "BM" "BT" "BO" "BO" "BA" "BW" "BV" "BR" "IO" "BN" "BN" "BG" "BF" "BI" "KH" "CM" "CA" "CV" "KY" "CF" "TD" "CL" "CN" "CX" "CC" "CO" "KM" "CG" "CD" "CK" "CR" "CI" "CI" "HR" "CU" "CY" "CZ" "DK" "DJ" "DM" "DO" "EC" "EG" "SV" "GQ" "ER" "EE" "ET" "FK" "FO" "FJ" "FI" "FR" "GF" "PF" "TF" "GA" "GM" "GE" "DE" "GH" "GI" "GR" "GL" "GD" "GP" "GU" "GT" "GG" "GN" "GW" "GY" "HT" "HM" "VA" "HN" "HK" "HU" "IS" "IN" "ID" "IR" "IQ" "IE" "IM" "IL" "IT" "JM" "JP" "JE" "JO" "KZ" "KE" "KI" "KP" "KR" "KR" "KW" "KG" "LA" "LV" "LB" "LS" "LR" "LY" "LY" "LI" "LT" "LU" "MO" "MK" "MG" "MW" "MY" "MV" "ML" "MT" "MH" "MQ" "MR" "MU" "YT" "MX" "FM" "MD" "MC" "MN" "ME" "MS" "MA" "MZ" "MM" "MM" "NA" "NR" "NP" "NL" "AN" "NC" "NZ" "NI" "NE" "NG" "NU" "NF" "MP" "NO" "OM" "PK" "PW" "PS" "PA" "PG" "PY" "PE" "PH" "PN" "PL" "PT" "PR" "QA" "RE" "RO" "RU" "RU" "RW" "SH" "KN" "LC" "PM" "VC" "VC" "VC" "WS" "SM" "ST" "SA" "SN" "RS" "SC" "SL" "SG" "SK" "SI" "SB" "SO" "ZA" "GS" "SS" "ES" "LK" "SD" "SR" "SJ" "SZ" "SE" "CH" "SY" "TW" "TW" "TJ" "TZ" "TH" "TL" "TG" "TK" "TO" "TT" "TN" "TR" "TM" "TC" "TV" "UG" "UA" "AE" "GB" "US" "UM" "UY" "UZ" "VU" "VE" "VE" "VN" "VN" "VG" "VI" "WF" "EH" "YE" "ZM" "ZW")

  if [ -f "/etc/federated" ]; then
    . /etc/federated
    [ -z "$DOMAIN" ] && failcheck "/etc/federated doesn't include DOMAIN"
    [ -z "$COMPANY" ] && failcheck "/etc/federated doesn't include COMPANY"
    [ -z "$COUNTRY" ] && failcheck "/etc/federated doesn't include COUNTRY"
    [ -z "$BUNDLE" ] && failcheck "/etc/federated doesn't include BUNDLE"
    if ! printf '%s\0' "${COUNTRIES[@]}" | grep -Fxqz -- "$COUNTRY"; then
      failcheck "$COUNTRY is not a valid country code. Use US, GB, HK, etc" 
    fi
    [ -z "$B2_APPLICATION_KEY_ID" ] && echo -ne "\nWarning: B2_APPLICATION_KEY_ID doesn't exist in /etc/federated\nBackups will be disabled"
    [ -z "$B2_APPLICATION_KEY" ] && echo -ne "\nWarning: B2_APPLICATION_KEY doesn't exist in /etc/federated\nBackups will be disabled"
  else
    failcheck "/etc/federated doesn't exist"
  fi 

  # Setup DOMAIN variable for domain or subdomain
  DOMAIN_ARRAY=(${DOMAIN//./ })
  if [ "${#DOMAIN_ARRAY[@]}" -eq "2" ]; then
    DOMAIN_FIRST=${DOMAIN_ARRAY[0]}
    DOMAIN_LAST=${DOMAIN_ARRAY[1]}
  elif [ "${#DOMAIN_ARRAY[@]}" -eq "3" ]; then
    DOMAIN_FIRST=${DOMAIN_ARRAY[0]}
    DOMAIN_MIDDLE=${DOMAIN_ARRAY[1]}
    DOMAIN_LAST=${DOMAIN_ARRAY[2]}
  else
    failcheck "$DOMAIN is not a valid domain.com or sub.domain.com"
  fi
}

while getopts d OPTION; do
  case "$OPTION" in
    d) DEBUG=ON;;
  esac
done

# Download lib scripts and take in setup variables
get_config

echo -ne "\nStarting Federated install for $DOMAIN\n"

# Check that we have docker installed.  Check that
# we have all ports available and not in use
check_docker
check_os
#check_memory
check_ports

# Configure docker private network
config_network

# Setup SERVICES array to what bundle
if [ "$BUNDLE" = "starter" ]; then
  SERVICES=("pdnsmysql" "pdns" "pdnsadmin" "traefik" "postgresql" "ldap" "mail" "collabora" "nextcloud" "autodiscover" "panel" "vaultwarden")
elif [ "$BUNDLE" = "team" ]; then
  SERVICES=("pdnsmysql" "pdns" "pdnsadmin" "traefik" "postgresql" "ldap" "mail" "collabora" "nextcloud" "autodiscover" "panel" "vaultwarden" "matrix" "element" "coturn" "wordpress" "freescout" "espocrm")
elif [ "$BUNDLE" = "creator" ]; then
  SERVICES=("pdnsmysql" "pdns" "pdnsadmin" "traefik" "postgresql" "ldap" "mail" "collabora" "nextcloud" "autodiscover" "panel" "vaultwarden" "matrix" "element" "coturn" "wordpress")
elif [ "$BUNDLE" = "ultimate" ]; then
  SERVICES=("pdnsmysql" "pdns" "pdnsadmin" "traefik" "postgresql" "ldap" "mail" "collabora" "nextcloud" "matrix" "element" "listmonk" "vaultwarden" "panel" "wireguard" "jitsi" "baserow" "gitea" "caddy" "autodiscover" "castopod" "wordpress" "coturn" "bookstack" "freescout" "msp" "espocrm")
else
  SERVICES=("pdnsmysql" "pdns" "pdnsadmin" "traefik" "postgresql" "ldap" "mail" "collabora" "nextcloud" "matrix" "element" "listmonk" "vaultwarden" "panel" "wireguard" "jitsi" "baserow" "gitea" "caddy" "autodiscover" "castopod" "wordpress" "coturn" "bookstack" "freescout" "msp" "espocrm")
fi

# Get apps that need to be installed and create array for it
#IFS=$'\n' read -r -d '' -a CORE_APPS_LIST < <(awk -F',' '{ for( i=1; i<=NF; i++ ) print $i }' <<<"$CORE_APPS")
#IFS=$'\n' read -r -d '' -a EXTRA_APPS_LIST < <(awk -F',' '{ for( i=1; i<=NF; i++ ) print $i }' <<<"$EXTRA_APPS")
#SERVICES=("${CORE_APPS_LIST[@]}" "${EXTRA_APPS_LIST[@]}")

# Configure and start each federated app
for i in "${SERVICES[@]}"; do
        . /federated/lib/$i.sh
	config_$i
	start_$i
done

# Add cron jobs for backup, upgrade, dumpcerts
add_cron

# Print out federated environment details
echo -ne "\n\n"
if [ "$BUNDLE" = "starter" ]; then
  print_details_starter
elif [ "$BUNDLE" = "team" ]; then
  print_details_team
elif [ "$BUNDLE" = "creator" ]; then
  print_details_creator
elif [ "$BUNDLE" = "ultimate" ]; then
  print_details
else
  print_details
fi
echo -ne "\n\n"
exit 0
