#!/bin/bash

# does /usr/share/nextcloud exists ? no: we create it from sources
if [ ! -f /usr/share/nextcloud/occ ]; then
  mkdir -p  /usr/share/nextcloud	
  chown root:www /usr/share/nextcloud
  rsync -arv -q  /usr/share/nextcloud-src/ /usr/share/nextcloud
fi
chmod 775 /usr/share/nextcloud

# important configuration variables
password=`/sbin/e-smith/db configuration getprop nextcloud DbPassword || echo "missing"`
dbname=`/sbin/e-smith/db configuration getprop nextcloud DbName || echo "nextcloud"`
dbuser=`/sbin/e-smith/db configuration getprop nextcloud DbUser || echo "nextcloud"`
adminuser=`/sbin/e-smith/db configuration getprop nextcloud AdminUser || echo "admin"`
adminpass=`/sbin/e-smith/db configuration getprop nextcloud AdminPassword ||/sbin/e-smith/db configuration getprop sysconfig SystemID  || echo "password;109"`
domain=`/sbin/e-smith/db configuration get DomainName|| echo "localhost"`

host="localhost:/var/lib/mysql/mysql.sock"
socket="--socket=/var/lib/mysql/mysql.sock"
# need to check what db we are supposed to use. starting NC 21 mariadb >= 102 is needed  core is 55
# are we fresh install or update ?
installed=$(/usr/bin/occ status --output json |jq -r '.installed')
# what version
majversion=$(/usr/bin/occ status --output json |jq -r '.version'|cut -d'.' -f1)

# initialize grants mysql nextcloud database
/usr/bin/mariadb --defaults-file=/root/.my.cnf $socket -e "CREATE DATABASE IF NOT EXISTS $dbname;"
/usr/bin/mariadb --defaults-file=/root/.my.cnf $socket -e "grant all on $dbname.* to '$dbuser'@'localhost' identified by '$password';"
/usr/bin/mariadb --defaults-file=/root/.my.cnf $socket -e "FLUSH PRIVILEGES"

res=`/usr/bin/mariadb --defaults-file=/root/.my.cnf $socket -e "select count(*) from information_schema.tables where table_type = 'BASE TABLE' and table_schema = '$dbname'" | tail -n1`;

#TODO : SME11 we need to see if db nextcloud exist
# if not we must check if /home/e-smith/db/mariadb105/nexcloud.dump exists and import it
# if not  we must check if /home/e-smith/db/mysql/nexcloud.dump exists and import it
## those might be skipped if the /usr/share/nextcloud had to be created
if [[ $res == '0' ]]; then
  if  [ -f /home/e-smith/db/mariadb105/nexcloud.dump ]; then
     echo "Mariadb database empty and there was a backup in /home/e-smith/db/mariadb105/nexcloud.dump; restoring it ..."
     /usr/bin/mariadb --defaults-file=/root/.my.cnf $socket $dbname < /home/e-smith/db/mariadb105/nexcloud.dump && mv /home/e-smith/db/mariadb105/nexcloud.dump /home/e-smith/files/nextcloud/data/mariadb105-nexcloud.dump
     /usr/bin/occ upgrade -n
  elif [ -f /home/e-smith/db/myslq/nexcloud.dump ]; then
     echo "Mariadb database empty and there was a backup in /home/e-smith/db/myslq/nexcloud.dump; restoring it ..."
     /usr/bin/mariadb --defaults-file=/root/.my.cnf $socket $dbname < /home/e-smith/db/mariadb105/nexcloud.dump
     /usr/bin/occ upgrade -n
  else  
      echo "Fresh install detected, starting occ maintenance:install procedure..."
     /usr/bin/occ maintenance:install --database mysql --database-host $host  --database-name $dbname --database-user $dbuser --database-pass $password --admin-user $adminuser --admin-pass  $adminpass --data-dir /home/e-smith/files/nextcloud/data/
    
     /usr/bin/occ app:enable user_ldap
     # might create s01 or empty id depending on version
     /usr/bin/occ ldap:create-empty-config 
     # create config with id s01 if not already present
     /usr/bin/occ ldap:show-config s01 1>/dev/null || /usr/bin/occ ldap:create-empty-config 
     # delete config with empty id if exist
     /usr/bin/occ ldap:delete-config '' 1>/dev/null 
  fi
else
  echo "We are reinstalling Nextcloud with an already populated mariadb database"
  if  [ -f /home/e-smith/db/mariadb105/nexcloud.dump ]; then
      echo "if you did a SME10 to SME11 migration: /home/e-smith/db/mariadb105/nexcloud.dump has been detected !!!"
      echo " ! check that you did not also migrate an older nextcloud.dump from SME10 mariadb 5.5 !"
  fi
  echo "Trying to upgrade"
  /usr/bin/occ upgrade -n
fi

mkdir -p /home/e-smith/files/nextcloud/skeleton/ibays
/usr/bin/occ config:system:set  skeletondirectory --value="/home/e-smith/files/nextcloud/skeleton"
#/usr/bin/occ config:system:set  templatedirectory --value=""

# prepare geoip2.phar and custom apps
echo "downloading  geoip2.phar for usage with geoblocker app..."
curl -q https://api.github.com/repos/maxmind/GeoIP2-php/releases/latest | jq -r '.assets[] | select(.name | match("phar")) | .browser_download_url' | xargs wget -q -O /usr/share/GeoIP/geoip2.phar
# in case you do not want to install smeserver-geoip and set it, you could (credit: https://github.com/P3TERX/GeoLite.mmdb)
#wget https://git.io/GeoLite2-Country.mmdb -O /usr/share/GeoIP/GeoLite2-Country.mmdb

# to satisfy code integrity check
if [ -f /usr/share/nextcloud/.htaccess.rpmsave ]; then
    rm -f /usr/share/nextcloud/.htaccess.rpmsave
fi
if [ -f /usr/share/nextcloud/.htaccess.rpmnew ]; then
    rm -f /usr/share/nextcloud/.htaccess.rpmnew
fi

# upgrade and check integrity
echo "upgrading nextcloud database..."
/usr/bin/occ upgrade
/usr/bin/occ maintenance:mode --off
/usr/bin/occ integrity:check-core
## Catch 'Nextcloud is already latest version' message
#if [ $? -eq 3 ]; then
#    exit 0
#fi

# remove signup link
echo "removing signup link..."
/usr/bin/occ config:system:set --type=bool --value=false simpleSignUpLink.shown

# set default values for sending mail 
echo "setting default value to allow to send mail, you can change them from basic settings..."
/usr/bin/occ config:system:get mail_from_address  || /usr/bin/occ config:system:set mail_from_address --type string --value="admin"
/usr/bin/occ config:system:get mail_smtpmode      || /usr/bin/occ config:system:set mail_smtpmode     --type string --value="smtp"
/usr/bin/occ config:system:get mail_sendmailmode  || /usr/bin/occ config:system:set mail_sendmailmode --type string --value="smtp"
/usr/bin/occ config:system:get mail_domain        || /usr/bin/occ config:system:set mail_domain       --type string --value=`/usr/sbin/e-smith/config get DomainName`
/usr/bin/occ config:system:get mail_smtpport      || /usr/bin/occ config:system:set mail_smtpport     --type string --value=`/usr/sbin/e-smith/config getprop qpsmtpd TCPPort`
/usr/bin/occ config:system:get mail_smtphost      || /usr/bin/occ config:system:set mail_smtphost     --type string --value=`/usr/sbin/e-smith/config get DomainName`

# install notify_push
/usr/bin/occ app:install notify_push

# install geoblocker
/usr/bin/occ app:install geoblocker
/usr/bin/occ config:app:set geoblocker MaxMindGeoLite2_DatabaseFileLocation --value "/usr/share/GeoIP/GeoLite2-Country.mmdb"
/usr/bin/occ config:app:set geoblocker chosenService  --value "1"

# set external password
/usr/bin/occ app:install externalpassword
/usr/bin/occ config:app:get externalpassword changePasswordUrl || /usr/bin/occ config:app:set  externalpassword changePasswordUrl --value "https://$domain/smanager"

#set default loglevel SME 12412
/usr/bin/occ config:system:set loglevel --value=3

#Redis index File Cache
echo "configuring setting for Redis..."
/usr/bin/occ config:system:set  redis host --value="localhost"
/usr/bin/occ config:system:set  redis port --value="6379"
/usr/bin/occ config:system:set  redis timeout --value="0.0"
/usr/bin/occ config:system:set  redis password --value=""
/usr/bin/occ config:system:set  memcache.locking --value="\OC\Memcache\Redis"
/usr/bin/occ config:system:set --type=bool --value=true filelocking.enabled

# cron maintenance windows
/usr/bin/occ config:system:set maintenance_window_start --type=integer --value=1

#samba needed folder to put gencache.tdb
if [ ! -d /var/www/.cache/samba ]; then
  mkdir -p /var/www/.cache/samba
  chown www:shared /var/www/.cache/samba
fi
if [ ! -d /home/e-smith/.cache/samba ]; then
  mkdir -p /home/e-smith/.cache/samba
  chown www:admin /home/e-smith/.cache/samba
fi


