#!/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
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

  read -ra CORE_APPS <<< "$CORE_APPS_ARG"
  read -ra EXTRA_APPS <<< "$EXTRA_APPS_ARG"

  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]}
  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 [[ "$ID" = "openmandriva" ]]; then
  # Small and useful enough for "docker logs [tab]" and friends
  dnf -y --refresh install bash-completion
  command -v dig &>/dev/null || dnf -y install bind-utils
  command -v git &>/dev/null || dnf -y install git-core
  command -v crontab &>/dev/null || dnf -y install cronie
  systemctl enable --now cronie
  # Make cronie happy
  mkdir -p /root/.cache || :
  command -v nc &>/dev/null || dnf -y install netcat-openbsd
  command -v htpasswd &>/dev/null || dnf -y install apache-tools
  command -v openssl &>/dev/null || dnf -y install openssl
  check_docker
  check_os
  check_ports
elif [[ "$NAME" = "Alpine Linux" ]]; then
  update_alpine
  install_packages_alpine
fi

# Configure docker private network
config_network

# Create a swap file if we're in a low RAM configuration
MEM=$(LC_ALL=C free |grep ^Mem: |awk '{ print $2; }')
if [ "$MEM" -le 2097152 ]; then
	SWAPSIZE=4096
elif [ "$MEM" -le 4194304 ]; then
	SWAPSIZE=2048
else
	SWAPSIZE=0
fi
if [ "$SWAPSIZE" -gt 0 ]; then
	touch /swap-0001
	chattr +C /swap-0001 || : # Disable copy-on-write for btrfs
	dd if=/dev/zero of=/swap-0001 bs=1M count=$SWAPSIZE
	chmod 0600 /swap-0001
	mkswap -v1 /swap-0001
	echo '/swap-0001 none swap defaults,prio=90 0 2' >>/etc/fstab
	swapon -a
fi

# 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
  if [ "x$PARALLEL_STARTUP" != "xfalse" ]; then
    start_$i &
  else
    # Startup in sequence is slower, but produces much
    # clearer debug output on an installation failure
    start_$i
  fi
done

wait

# Configure SSO for each app
for i in "${EXTRA_APPS[@]}"; do
  . /federated/lib/$i.sh
  [[ $(type -t configsso_$i) == function ]] && configsso_$i
done

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

echo -ne "\n\n"
exit 0
