#!/bin/bash -x
#
# NextCloud Service

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

config_nextcloud() {
  echo -ne "\n* Configuring /federated/apps/nextcloud container.."
  spin &
  SPINPID=$!

  if [ ! -d "/federated/apps/nextcloud" ]; then
    mkdir -p /federated/apps/nextcloud/data/root &> /dev/null
    mkdir -p /federated/apps/nextcloud/data/home &> /dev/null
    mkdir -p /federated/apps/nextcloud/data/var/www/html &> /dev/null
    mkdir -p /federated/apps/nextcloud/data/var/www/html/custom_apps &> /dev/null
    mkdir -p /federated/apps/nextcloud/data/var/www/config &> /dev/null
    mkdir -p /federated/apps/nextcloud/data/var/www/data &> /dev/null
    mkdir -p /federated/apps/nextcloud/data/usr/local/etc/php/conf.d &> /dev/null
  fi

cat > /federated/apps/nextcloud/docker-compose.yml <<EOF
version: '3.7'

services:
  nextcloud:
    image: nextcloud:\${IMAGE_VERSION}
    container_name: nextcloud
    hostname: nextcloud.$DOMAIN
    domainname: $DOMAIN
    restart: always
#    working_dir: /var/www/html
    networks:
      federated:
        ipv4_address: 172.99.0.18
    extra_hosts:
      - "collabora.$DOMAIN:$EXTERNALIP"
    volumes:
      - ./data/root:/root
      - ./data/home:/home
      - ./data/var/www/html:/var/www/html
      - ./data/var/www/html/custom_apps:/var/www/html/custom_apps
      - ./data/var/www/config:/var/www/config
      - ./data/var/www/data:/var/www/data
      - ./data/usr/local/etc/php/conf.d/opcache-recommended.ini:/usr/local/etc/php/conf.d/opcache-recommended.ini
      - ./data/usr/local/etc/php/conf.d/docker-php-ext-apcu.ini:/usr/local/etc/php/conf.d/docker-php-ext-apcu.ini
    env_file:
      - ./.env
    secrets:
      - federated_psql_password
      - federated_nextcloud_password
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.nextcloud.rule=Host(\`nextcloud.$DOMAIN\`)"
      - "traefik.http.routers.nextcloud.entrypoints=websecure"
      - "traefik.http.routers.nextcloud.tls.certresolver=letsencrypt"
      - "traefik.http.routers.nextcloud.middlewares=nextcloud-redirectregex1,nextcloud-redirectregex2,nextcloudheader"
      - "traefik.http.middlewares.nextcloud-redirectregex1.redirectregex.permanent=true"
      - "traefik.http.middlewares.nextcloud-redirectregex1.redirectregex.regex=https?://([^/]*)/.well-known/(card|cal)dav"
      - "traefik.http.middlewares.nextcloud-redirectregex1.redirectregex.replacement=https://\$\${1}/remote.php/dav/"
      - "traefik.http.middlewares.nextcloud-redirectregex2.redirectregex.permanent=true"
      - "traefik.http.middlewares.nextcloud-redirectregex2.redirectregex.regex=https?://([^/]*)(/.well-known[^#]*)"
      - "traefik.http.middlewares.nextcloud-redirectregex2.redirectregex.replacement=https://\$\${1}/index.php\$\${2}"
      - "traefik.http.middlewares.nextcloudheader.headers.stsSeconds=15552000"
      - "traefik.http.middlewares.nextcloudheader.headers.stsIncludeSubdomains=true"
      - "traefik.http.middlewares.nextcloudheader.headers.stsPreload=true"
      - "traefik.http.middlewares.nextcloudheader.headers.forceSTSHeader=true"

secrets:
  federated_psql_password:
    file: ./.postgresql.secret
  federated_nextcloud_password:
    file: ./.nextcloud.secret
networks:
  federated:
    external: true
EOF

LDAP_SECRET=`cat /federated/apps/ldap/.ldap.secret`
echo "$NEXTCLOUD_SECRET" > /federated/apps/nextcloud/.postgresql.secret
echo "$ADMINPASS" > /federated/apps/nextcloud/.nextcloud.secret
chmod 600 /federated/apps/nextcloud/.postgresql.secret /federated/apps/nextcloud/.nextcloud.secret

cat > /federated/apps/nextcloud/.env <<EOF
IMAGE_VERSION=28.0
NEXTCLOUD_UPDATE=1
PHP_MEMORY_LIMIT=2048M
PHP_UPLOAD_LIMIT=2048M
TRUSTED_PROXIES=172.99.0.0/16
NEXTCLOUD_TRUSTED_DOMAINS=nextcloud.$DOMAIN
NEXTCLOUD_ADMIN_USER=nextcloud
NEXTCLOUD_ADMIN_PASSWORD_FILE=/run/secrets/federated_nextcloud_password
POSTGRES_HOST=postgresql.$DOMAIN
POSTGRES_DB=nextcloud
POSTGRES_USER=nextcloud
POSTGRES_PASSWORD_FILE=/run/secrets/federated_psql_password
EOF
chmod 600 /federated/apps/nextcloud/.env

cat > /federated/apps/nextcloud/data/usr/local/etc/php/conf.d/opcache-recommended.ini <<EOF
opcache.enable=1
opcache.interned_strings_buffer=32
opcache.max_accelerated_files=18000
opcache.memory_consumption=256
opcache.save_comments=1
opcache.revalidate_freq=60
EOF

cat > /federated/apps/nextcloud/data/usr/local/etc/php/conf.d/docker-php-ext-apcu.ini <<EOF
extension=apcu
apc.enable_cli=1
apc.shm_size=256M
apc.ttl=3600
apc.user_ttl=7200
apc.gc_ttl=3600
apc.max_file_size=2M
EOF

cat > /federated/apps/nextcloud/data/configs.json <<EOF
{
   "system": {
        "mail_smtpmode": "smtp",
        "mail_smtpsecure": "tls",
        "mail_sendmailmode": "smtp",
        "mail_from_address": "nextcloud",
        "mail_domain": "$DOMAIN",
        "mail_smtpauthtype": "LOGIN",
        "mail_smtpauth": 1,
        "mail_smtphost": "mail.$DOMAIN",
        "mail_smtpport": "587",
        "mail_smtpname": "fcore",
        "mail_smtppassword": "$ADMINPASS"
   },
   "apps": {
        "core": {
            "backgroundjobs_mode": "cron"
        },
	"side_menu": {
            "background-color-opacity": "100",
            "current-app-background-color": "#005b8d",
            "types": "",
            "enabled": "yes",
            "text-color": "#ffffff",
            "loader-color": "#339bd4",
            "types": "",
            "always-displayed": "0",
            "big-menu": "0",
            "side-with-categories": "0",
            "background-color": "#0068a1",
            "background-color-to": "#0068a1",
            "icon-invert-filter": "0",
            "icon-opacity": "100",
            "opener": "side-menu-opener",
            "dark-mode-background-color": "#0068a1",
            "dark-mode-background-color-to": "#0068a1",
            "dark-mode-background-color-opacity": "100",
            "dark-mode-current-app-background-color": "#005b8d",
            "dark-mode-text-color": "#ffffff",
            "dark-mode-loader-color": "#ffffff",
            "dark-mode-icon-invert-filter": "0",
            "dark-mode-icon-opacity": "100",
            "dark-mode-opener": "side-menu-opener",
            "opener-position": "before",
            "opener-only": "0",
            "hide-when-no-apps": "0",
            "opener-hover": "0",
            "display-logo": "1",
            "use-avatar": "0",
            "add-logo-link": "1",
            "big-menu-hidden-apps": "[]",
            "show-settings": "0",
            "size-icon": "normal",
            "size-text": "normal",
            "target-blank-apps": "[]",
            "loader-enabled": "1",
            "top-side-menu-apps": "[]",
            "top-menu-mouse-over-hidden-label": "0",
            "apps-order": "[\"dashboard\",\"mail\",\"calendar\",\"contacts\",\"notes\",\"tasks\",\"files\",\"deck\",\"bookmarks\",\"forms\",\"spreed\",\"photos\",\"activity\"]",
            "categories-order-type": "default",
            "categories-custom": "[]",
            "apps-categories-custom": "[]",
            "categories-order": "[\"other\",\"customization\",\"dashboard\",\"external_links\",\"files\",\"workflow\",\"games\",\"integration\",\"monitoring\",\"multimedia\",\"office\",\"organization\",\"search\",\"security\",\"social\",\"tools\"]",
            "default-enabled": "1",
            "force": "0",
            "top-menu-apps": "[\"photos\",\"activity\",\"dashboard\",\"forms\",\"calendar\",\"tasks\",\"bookmarks\",\"deck\",\"contacts\",\"notes\",\"spreed\",\"mail\",\"files\"]",
            "cache": "2"
	}
   }
}
EOF

cat > /federated/apps/nextcloud/data/config.sh <<EOF
#!/bin/sh

PATH=/var/www/html:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/sbin:/bin

/var/www/html/occ app:enable user_ldap
/var/www/html/occ ldap:create-empty-config
/var/www/html/occ ldap:set-config s01 ldapHost 'ldaps://ldap.$DOMAIN'
/var/www/html/occ ldap:set-config s01 ldapAgentName cn=admin,dc=federatedcomputer,dc=cloud
/var/www/html/occ ldap:set-config s01 ldapAgentPassword $LDAP_SECRET
/var/www/html/occ ldap:set-config s01 ldapBase ou=people,dc=federatedcomputer,dc=cloud
/var/www/html/occ ldap:set-config s01 ldapBaseGroups ou=groups,dc=federatedcomputer,dc=cloud
/var/www/html/occ ldap:set-config s01 ldapBaseUsers ou=people,dc=federatedcomputer,dc=cloud
/var/www/html/occ ldap:set-config s01 ldapEmailAttribute mail
/var/www/html/occ ldap:set-config s01 ldapGidNumber gidNumber
/var/www/html/occ ldap:set-config s01 ldapGroupDisplayName cn
/var/www/html/occ ldap:set-config s01 ldapGroupFilter '(&(|(objectclass=posixGroup)))'
/var/www/html/occ ldap:set-config s01 ldapGroupFilterMode 0
/var/www/html/occ ldap:set-config s01 ldapGroupFilterObjectclass inetOrgPerson
/var/www/html/occ ldap:set-config s01 ldapGroupMemberAssocAttr uniqueMember
/var/www/html/occ ldap:set-config s01 ldapLoginFilter '(&(|(objectclass=inetOrgPerson))(mail=%uid))'
/var/www/html/occ ldap:set-config s01 ldapLoginFilterEmail 0
/var/www/html/occ ldap:set-config s01 ldapLoginFilterMode 0
/var/www/html/occ ldap:set-config s01 ldapLoginFilterUsername 1
/var/www/html/occ ldap:set-config s01 ldapLoginFilterEmail 0
/var/www/html/occ ldap:set-config s01 ldapMatchingRuleInChainState unknown
/var/www/html/occ ldap:set-config s01 ldapNestedGroups 0
/var/www/html/occ ldap:set-config s01 ldapPagingSize 500 
/var/www/html/occ ldap:set-config s01 ldapPort 636
/var/www/html/occ ldap:set-config s01 ldapTLS 1 
/var/www/html/occ ldap:set-config s01 ldapUserAvatarRule default
/var/www/html/occ ldap:set-config s01 ldapUserDisplayName cn
/var/www/html/occ ldap:set-config s01 ldapUserFilter '(|(objectclass=inetOrgPerson))'
/var/www/html/occ ldap:set-config s01 ldapUserFilterMode 0 
/var/www/html/occ ldap:set-config s01 ldapUserFilterObjectclass inetOrgPerson
/var/www/html/occ ldap:set-config s01 ldapUuidGroupAttribute auto
/var/www/html/occ ldap:set-config s01 ldapUuidUserAttribute auto 
/var/www/html/occ ldap:set-config s01 turnOffCertCheck 0 
/var/www/html/occ ldap:set-config s01 turnOnPasswordChange 0 
/var/www/html/occ ldap:set-config s01 useMemberOfToDetectMembership 1 
/var/www/html/occ ldap:set-config s01 ldapConfigurationActive 1 
/var/www/html/occ ldap:set-config s01 ldap_expert_username_attr uid
/var/www/html/occ ldap:set-config s01 ldap_display_name givenName
/var/www/html/occ config:system:set overwriteprotocol --value=https
/var/www/html/occ config:system:set default_phone_region --value="$COUNTRY"
/var/www/html/occ config:system:delete trusted_domains
/var/www/html/occ config:system:set trusted_domains 1 --value=*
/var/www/html/occ group:adduser admin admin
/var/www/html/occ user:delete nextcloud
/var/www/html/occ app:enable mail
/var/www/html/occ app:enable calendar
/var/www/html/occ app:enable contacts
/var/www/html/occ app:enable notes
/var/www/html/occ app:enable deck
/var/www/html/occ app:enable tasks
/var/www/html/occ app:enable bookmarks
/var/www/html/occ app:enable forms
/var/www/html/occ app:enable spreed
/var/www/html/occ app:enable side_menu
/var/www/html/occ app:enable external 
/var/www/html/occ app:enable richdocuments
/var/www/html/occ config:app:set --value https:\/\/collabora.$DOMAIN richdocuments public_wopi_url
/var/www/html/occ config:app:set --value https:\/\/collabora.$DOMAIN richdocuments wopi_url
/var/www/html/occ config:app:set --value ooxml richdocuments doc_format
/var/www/html/occ config:app:set --value "" richdocuments disable_certificate_verification
/var/www/html/occ config:app:set external sites "--value={\"1\":{\"icon\":\"external.svg\",\"lang\":\"\",\"type\":\"link\",\"device\":\"browser\",\"groups\":[],\"redirect\":true,\"id\":1,\"name\":\"Video Conference (Jitsi)\",\"url\":\"https:\/\/jitsi.$DOMAIN\"},\"2\":{\"icon\":\"external.svg\",\"lang\":\"\",\"type\":\"link\",\"device\":\"browser\",\"groups\":[],\"redirect\":true,\"id\":2,\"name\":\"Worldwide Chat (Element)\",\"url\":\"https:\/\/element.$DOMAIN\"},\"3\":{\"icon\":\"external.svg\",\"lang\":\"\",\"type\":\"link\",\"device\":\"browser\",\"groups\":[],\"redirect\":true,\"id\":3,\"name\":\"Mailing Lists (Listmonk)\",\"url\":\"https:\/\/listmonk.$DOMAIN\"},\"4\":{\"icon\":\"external.svg\",\"lang\":\"\",\"type\":\"link\",\"device\":\"browser\",\"groups\":[],\"redirect\":true,\"id\":4,\"name\":\"Databases (Baserow)\",\"url\":\"https:\/\/baserow.$DOMAIN\"},\"5\":{\"icon\":\"external.svg\",\"lang\":\"\",\"type\":\"link\",\"device\":\"browser\",\"groups\":[],\"redirect\":true,\"id\":5,\"name\":\"Passwords (Vaultwarden)\",\"url\":\"https:\/\/vaultwarden.$DOMAIN\"},\"7\":{\"icon\":\"external.svg\",\"lang\":\"\",\"type\":\"link\",\"device\":\"browser\",\"groups\":[],\"redirect\":true,\"id\":7,\"name\":\"Source code (Gitea)\",\"url\":\"https:\/\/gitea.$DOMAIN\"}}"
/var/www/html/occ config:import configs.json
EOF

chmod +x /federated/apps/nextcloud/data/config.sh

  kill -9 $SPINPID &> /dev/null
  echo -ne "done."
}

start_nextcloud() {
  # Start service with command to make sure it's up before proceeding
  start_service "nextcloud" "nc -z 172.99.0.18 80 &> /dev/null" "35"

  # Move config.sh and sidemenu config, set config.sh executable
  mv /federated/apps/nextcloud/data/config.sh /federated/apps/nextcloud/data/configs.json /federated/apps/nextcloud/data/var/www/html/
  docker exec nextcloud chown www-data:root /var/www/html/config.sh /var/www/html/configs.json
  docker exec nextcloud chmod 755 /var/www/html/config.sh
  [ $? -ne 0 ] && fail "Couldn't chown config.sh in /federated/apps/nextcloud container"

  # Run config.sh - Setup LDAP, configuration for nextcloud
  docker exec -u 33 nextcloud /var/www/html/config.sh &> /dev/null
  [ $? -ne 0 ] && fail "Couldn't run config.sh inside /federated/apps/nextcloud container"

  # Add admin user to group
  # Have to do it this many times so it will query LDAP and populate admin user first
  docker exec -u 33 nextcloud /var/www/html/occ ldap:search admin
  docker exec -u 33 nextcloud /var/www/html/occ group:list
  docker exec -u 33 nextcloud /var/www/html/occ group:adduser admin admin
  docker exec -u 33 nextcloud /var/www/html/occ group:adduser admin admin
  docker exec -u 33 nextcloud /var/www/html/occ group:list

  # Setup admin email account
  docker exec -u 33 nextcloud bash -c "/var/www/html/occ mail:account:create admin admin admin@$DOMAIN mail.$DOMAIN 993 ssl admin@$DOMAIN $ADMINPASS mail.$DOMAIN 465 ssl admin@$DOMAIN $ADMINPASS password" &> /dev/null

  # Add missing indexes and disable activity app
  docker exec -u 33 nextcloud /var/www/html/occ db:add-missing-indices
  docker exec -u 33 nextcloud /var/www/html/occ app:disable activity

  # Remove configs
  rm /federated/apps/nextcloud/data/var/www/html/config.sh /federated/apps/nextcloud/data/var/www/html/configs.json

  kill -9 $SPINPID &> /dev/null
  echo -ne "done."
}
