#!/bin/bash
set -e

ERROR_FILE=/dev/stderr
while [ "$1" != "" ]; do
    case $1 in
        --error-file)
            shift
            ERROR_FILE=$1
            ;;
        *)
            PARAM=`echo $1 | awk -F= '{print $1}'`
            VALUE=`echo $1 | awk -F= '{print $2}'`
            case $PARAM in
                --error-file)
                    ERROR_FILE=$VALUE
                    ;;
            esac
            ;;
    esac
    shift
done

if [ ! -f /etc/mysql.secret ]; then
    # MySQL not yet installed
    echo "Altering MySQL configuration prior to database installation."
    ucr set mysql/config/mysqld/innodb_file_format=Barracuda \
            mysql/config/mysqld/innodb_large_prefix=1        \
            mysql/config/mysqld/innodb_file_per_table=1      \
            mysql/config/mysqld/max_allowed_packet=1G
else
  echo "Checking MariaDB configuration..."
  MYSQL="mysql -uroot -p$(cat /etc/mysql.secret) -ss"

  # check innodb_file_format, innodb_large_prefix, innodb_file_per_table and max_allowed_packet
  INNODB_FILE_FORMAT=$(($MYSQL -e 'SELECT @@GLOBAL.innodb_file_format;' 2>/dev/null) || echo "Barracuda" )
  echo "    innodb_file_format="$INNODB_FILE_FORMAT

  INNODB_LARGE_PREFIX=$(($MYSQL -e 'SELECT @@GLOBAL.innodb_large_prefix;' 2>/dev/null) || echo "1" )
  echo "    innodb_large_prefix="$INNODB_LARGE_PREFIX

  INNODB_FILE_PER_TABLE=$($MYSQL -e 'SELECT @@GLOBAL.innodb_file_per_table;')
  echo "    innodb_file_per_table="$INNODB_FILE_PER_TABLE

  MAX_ALLOWED_PACKET=$($MYSQL -e 'SELECT @@GLOBAL.max_allowed_packet;')
  echo "    max_allowed_packet="$MAX_ALLOWED_PACKET

  if [ $INNODB_FILE_FORMAT = "Antilope" -o $INNODB_LARGE_PREFIX -eq 0 -o $INNODB_FILE_PER_TABLE -eq 0 -o $MAX_ALLOWED_PACKET -lt 1073741824 ]; then
      echo "Altering MySQL configuration and restarting database."
      ucr set mysql/config/mysqld/innodb_file_format=Barracuda \
              mysql/config/mysqld/innodb_large_prefix=1        \
              mysql/config/mysqld/innodb_file_per_table=1      \
              mysql/config/mysqld/max_allowed_packet=1G
      service mysql restart
  fi

  if [ -e /etc/mysql-relution.secret ]; then
      # check relution database charset and collation
      CHARSET=$($MYSQL -e "SELECT \`default_character_set_name\` from \`information_schema\`.\`SCHEMATA\` where \`schema_name\`='relution';")
      echo "    charset="$CHARSET

      COLLATION=$($MYSQL -e "SELECT \`default_collation_name\` from \`information_schema\`.\`SCHEMATA\` where \`schema_name\`='relution';")
      echo "    collation="$COLLATION
  else
      # check default database charset and collation
      CHARSET=$($MYSQL -e 'SELECT @@GLOBAL.character_set_server')
      echo "    charset="$CHARSET

      COLLATION=$($MYSQL -e 'SELECT @@GLOBAL.collation_server')
      echo "    collation="$COLLATION
  fi
  echo "done"
  echo
fi

# Make sure Relution user exists
echo "Test if relution user exists"
if ! id relution; then
    echo "Creating user relution..."
    adduser \
     --system \
     --disabled-login \
     --no-create-home \
     --home /nonexistent \
     --gecos "Relution" \
     --shell /bin/false \
     relution
fi
echo "done"
echo

#
# Create directory, if needed
#
echo "Create 'conf' directory, if needed"
mkdir -p /var/lib/univention-appcenter/apps/relution/conf
echo "done"
echo

# Create application.yml for LDAP access
echo "Create 'application.yml', if needed"
if [ ! -f /var/lib/univention-appcenter/apps/relution/conf/application.yml ]; then
  echo "Creating file..."
  cat > /var/lib/univention-appcenter/apps/relution/conf/application.yml << "EOF"
#
# LDAP configuration, see: https://live.relution.io/relution/docs/relution-installguide/advanced_setup/ldap.html
#
ldap:
  default:
    name: '${ORGA_FULLNAME:}'
    organizationUniqueName: '${ORGA_NAME:}'
    ldap_urls:
      - ${LDAP_URL:}
    ldap_userDn: ${LDAP_BIND_USER:}
    ldap_password_url: ${LDAP_BIND_PASSWORD_URL:}

    ldap_poolsize: 2
    ldap_refferal: ignore
    ldap_base: ${LDAP_BASE:}

    sync_users: true
    sync_interval: 24h
    user_searchScope: 2
    user_searchBase:
    user_searchFilterTemplate: '(&(uid=%v)(objectClass=person)(relutionActivated=TRUE))'
    manual_user_mapping: true
    user_attribute_foreignKey: entryUUID
    user_attribute_name: displayName
    user_attribute_email: mailPrimaryAddress

    sync_groups: true
    group_useGroups: true
    sync_groups_interval: 24h
    group_searchScope: 2
    group_searchBase: cn=groups
    group_searchFilterTemplate: '(&(cn=%v)(objectClass=groupofnames))'
    manual_group_mapping: true
    group_attribute_foreignKey: gidNumber
    group_attribute_member: uniqueMember

    group_syntheticGroup: 'LDAP Users'
    groupRoles_json: |
      {
        "%o LDAP Users": [
          "%o Appstore User",
          "%o Device User"
        ]
      }
EOF
fi
echo "done"
echo

# Create unset.sh to remove environment variables we don't need
echo "Create 'unset.sh'"
cat > /var/lib/univention-appcenter/apps/relution/conf/unset.sh << "EOF"
unset APPCENTER_INDEX_VERIFY
unset appcenter_index_verify
unset container
unset database_pwd
unset database_user
unset DB_HOST
unset db_host
unset DB_NAME
unset db_name
unset DB_PORT
unset db_port
unset DOCKER_HOST_NAME
unset docker_host_name
unset DOMAINNAME
unset domainname
unset hostname
unset ldap_base
unset ldap_hostdn
unset LDAP_MASTER
unset ldap_master
unset LDAP_MASTER_PORT
unset ldap_master_port
unset LDAP_SERVER_IP
unset ldap_server_ip
unset LDAP_SERVER_NAME
unset ldap_server_name
unset LDAP_SERVER_PORT
unset ldap_server_port
unset LDAP_SERVER_TYPE
unset ldap_server_type
unset LOCALE
unset locale
unset LOCALE_DEFAULT
unset locale_default
unset MYSQL_AUTOSTART
unset mysql_autostart
unset NAMESERVER1
unset nameserver1
unset NAMESERVER_EXTERNAL
unset nameserver_external
unset nameserver_option_timeout
unset NAMESERVER_OPTION_TIMEOUT
unset orga_admin_email
unset orga_admin_givenname
unset orga_admin_password
unset orga_admin_surname
unset orga_admin_username
unset orga_contact_email
unset orga_contact_name
unset orga_fullname
unset orga_name
unset orga_replytomail
unset REPOSITORY_APP_CENTER_SERVER
unset repository_app_center_server
unset REPOSITORY_ONLINE_SERVER
unset repository_online_server
unset SERVER_ROLE
unset server_role
unset smtp_host
unset smtp_password
unset smtp_port
unset smtp_ssl
unset smtp_ttls
unset smtp_username
unset system_admin_password
unset update_secure_apt
unset UPDATE_SECURE_APT
unset UPDATE_WARNING_RELEASENOTES
unset update_warning_releasenotes
unset updater_identify
unset UPDATER_IDENTIFY
EOF
echo "done"
echo

# Make unset.sh executable
echo "Make 'unset.sh' executable"
chmod +x "/var/lib/univention-appcenter/apps/relution/conf/unset.sh"
echo "done"
echo
