#!/bin/bash
#
# Panel Service

PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

config_panel() {
  echo -ne "* Configuring panel container.."

  if [ ! -d "/federated/apps/panel" ]; then
    mkdir -p /federated/apps/panel/data/opt/ldap_user_manager
  fi

cat > /federated/apps/panel/docker-compose.yml <<EOF
services:
  panel:
    image: wheelybird/ldap-user-manager:\${IMAGE_VERSION}
    container_name: panel
    hostname: panel.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.23
    env_file:
      - ./.env
    volumes:
      - ./data/opt/ldap_user_manager:/opt/ldap_user_manager
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.panel.rule=Host(\`panel.$DOMAIN\`)"
      - "traefik.http.routers.panel.entrypoints=websecure"
      - "traefik.http.routers.panel.tls.certresolver=letsencrypt"

networks:
  core:
    external: true
EOF

# Extract our modified PHP panel into panel /opt directory
tar zxvf /federated/lib/files/panel/ldapusermanager-* -C /federated/apps/panel/data/opt/ldap_user_manager/
[ $? -ne 0 ] && fail "Couldn't extract files/panel/ldapusermanager-* into data/opt/ldap_user_manager"

LDAP_SECRET=`cat /federated/apps/ldap/.ldap.secret`

cat > /federated/apps/panel/.env <<EOF
IMAGE_VERSION="$(current_version panel)"
SERVER_HOSTNAME=panel.$DOMAIN
LDAP_URI=ldap://ldap.$DOMAIN
LDAP_BASE_DN=dc=federatedcomputer,dc=cloud
LDAP_REQUIRE_STARTTLS=true
LDAP_ADMINS_GROUP=admins
LDAP_ADMIN_BIND_DN=cn=admin,dc=federatedcomputer,dc=cloud
LDAP_ADMIN_BIND_PWD=$LDAP_SECRET
LDAP_ACCOUNT_ADDITIONAL_OBJECTCLASSES=PostfixBookMailAccount
LDAP_ACCOUNT_ADDITIONAL_ATTRIBUTES=mailEnabled:Mail Enabled:TRUE,mailAlias+:Email aliases
EMAIL_DOMAIN=$DOMAIN
ENFORCE_SAFE_SYSTEM_NAMES=false
USERNAME_FORMAT={first_name}.{last_name}
SITE_LOGIN_LDAP_ATTRIBUTE=mail
SITE_LOGIN_FIELD_LABEL="Email Address"
SITE_NAME=$COMPANY User Manager
SMTP_HOSTNAME=mail.$DOMAIN
SMTP_USERNAME=fcore
SMTP_PASSWORD=$ADMINPASS
EMAIL_FROM_ADDRESS=panel@$DOMAIN
SMTP_USE_TLS=true
SMTP_HOST_PORT=587
NO_HTTPS=true
EOF
chmod 600 /federated/apps/panel/.env
 
echo -ne "done.\n"
}
start_panel() {
  # Start service with command to make sure it's up before proceeding
  start_service "panel" "nc -z 192.168.0.23 80 &> /dev/null" "7"

  echo -ne "done.\n"
}
