#!/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 "$TIER" ] && failcheck "/etc/federated doesn't include TIER"
    BUNDLE="$TIER"
    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 which OS.
# Check that we have docker installed.  Check that
# we have all ports available and not in use
. /etc/os-release
if [[ "$NAME" = "Ubuntu" ]]; then
  check_docker
  check_os
  #check_memory
  check_ports
elif [[ "$NAME" = "Alpine Linux" ]]; then
  update_alpine
  install_packages_alpine
fi

# Configure docker private network
config_network

# Setup arrays to what bundle
if [ "$BUNDLE" = "good" ]; then
  CORE_APPS=("pdnsmysql" "pdns" "pdnsadmin" "traefik" "postgresql" "ldap")
  EXTRA_APPS=("mail" "collabora" "nextcloud" "autodiscover" "panel" "vaultwarden" "dashboard" "roundcube" "wordpress" "wireguard")
elif [ "$BUNDLE" = "better" ]; then
  CORE_APPS=("pdnsmysql" "pdns" "pdnsadmin" "traefik" "postgresql" "ldap")
  EXTRA_APPS=("mail" "collabora" "nextcloud" "autodiscover" "panel" "vaultwarden" "dashboard" "roundcube" "wordpress" "wireguard" "matrix" "element" "jitsi" "espocrm")
elif [ "$BUNDLE" = "best" ]; then
  CORE_APPS=("pdnsmysql" "pdns" "pdnsadmin" "traefik" "postgresql" "ldap")
  EXTRA_APPS=("mail" "collabora" "nextcloud" "autodiscover" "panel" "vaultwarden" "dashboard" "roundcube" "wordpress" "wireguard" "matrix" "element" "jitsi" "espocrm" "baserow" "bookstack" "gitea" "freescout")
else
  CORE_APPS=("pdnsmysql" "pdns" "pdnsadmin" "traefik" "postgresql" "ldap")
  EXTRA_APPS=("mail" "collabora" "nextcloud" "autodiscover" "panel" "vaultwarden" "dashboard" "roundcube" "wordpress" "wireguard" "matrix" "element" "jitsi" "espocrm" "baserow" "bookstack" "gitea" "freescout")
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 core app
for i in "${CORE_APPS[@]}"; do
  . /federated/lib/$i.sh
  config_$i
  start_$i
done

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

wait

# Add cron jobs for backup, upgrade, dumpcerts
add_cron
run_finishtasks

# Print out federated environment details
echo -ne "\n\n"
if [ "$BUNDLE" = "starter" ]; then
  create_email_withoutvpn
elif [ "$BUNDLE" = "team" ]; then
  create_email_withoutvpn
elif [ "$BUNDLE" = "creator" ]; then
  create_email_withoutvpn
elif [ "$BUNDLE" = "enterprise" ]; then
  create_email_withvpn
else
  create_email_withvpn
fi
echo -ne "\n\n"
exit 0
