#!/bin/bash

# configure - Settings script configure run in Docker container
# es gibt Dinge, die nur im Docker Container selbst gemacht werden können:
# - nginx Konfiguration
# - "Passwort vergessen"-Link entfernen
# - Konfigurationsdateien anpassen

function init_ldap(){
  ldappass=`cat /etc/machine.secret`
  f="/opt/seafile/conf/ccnet.conf"
  sed -i "s|^SERVICE_URL.*|SERVICE_URL=https://${DOCKER_HOST_NAME}/seafile|" ${f}

  # New installation
  if ! grep -q "\[LDAP\]" ${f}; then
    echo "[LDAP]
HOST = ldap://${LDAP_SERVER_NAME}:${LDAP_SERVER_PORT}/
BASE = ${LDAP_BASE}
USER_DN = ${LDAP_HOSTDN}
PASSWORD = ${ldappass}
LOGIN_ATTR = mailPrimaryAddress
FILTER = seafileActivated=TRUE

[LDAP_SYNC]
ENABLE_USER_SYNC = true
DEACTIVE_USER_IF_NOTFOUND = true
SYNC_INTERVAL = 1
USER_OBJECT_CLASS = person
ENABLE_EXTRA_USER_INFO_SYNC = true
FIRST_NAME_ATTR = givenName
LAST_NAME_ATTR = sn
UID_ATTR = uid
CONTACT_EMAIL_ATTR = mailPrimaryAddress" >> ${f}

    # UPDATE (ccnet.conf already exists and LDAP credentials have to be updated only)
    else
      sed -i "s/USER_DN =.*/USER_DN = ${LDAP_HOSTDN}/"  ${f}
      sed -i "s/PASSWORD =.*/PASSWORD = ${ldappass}/"  ${f}

    fi
}

function init_seahub(){
  f="/opt/seafile/conf/seahub_settings.py"
  sed -i 's|^FILE_SERVER_ROOT.*|FILE_SERVER_ROOT = \"https://'${DOCKER_HOST_NAME}'/seafile/seafhttp\"|' ${f}
  if ! grep -q "SERVE_STATIC" ${f}; then
    echo 'SERVE_STATIC = False
MEDIA_URL = "/seafile/seafmedia/"
COMPRESS_URL = MEDIA_URL
STATIC_URL = MEDIA_URL + "assets/"
SITE_ROOT = "/seafile/"
LOGIN_URL = "/seafile/accounts/login/"' >> ${f}
  fi
  if ! grep -q "FILE_SERVER_ROOT" ${f}; then
    echo 'FILE_SERVER_ROOT = "https://'${DOCKER_HOST_NAME}'/seafile/seafhttp"' >> ${f}
  fi
}

function update_seafdav(){
  f="/opt/seafile/conf/seafdav.conf"
  seafdav_activate=`grep seafile/seafdav_activate /etc/univention/base.conf | sed "s|seafile/seafdav_activate:||" | tr -d '[:space:]'`
  echo SEAFDAV-STATUS: ${seafdav_activate}
  if [[ $seafdav_activate == "true" ]]; then
    echo '[WEBDAV]
enabled = true
port = 8080
fastcgi = false
share_name = /seafile/seafdav' > $f 
  else
    echo '[WEBDAV]
enabled = false
port = 8080
fastcgi = false
share_name = /seafile/seafdav' > $f 
  fi
}

function update_email(){
  f="/opt/seafile/conf/seahub_settings.py"
  backupdate=`date +%F_%T`
  f_bak="/opt/seafile/conf/seahub_settings.py_${backupdate}"
  cp ${f} ${f_bak}

  sed -i '/EMAIL_USE_TLS.*/d' ${f}
  sed -i '/EMAIL_HOST.*/d' ${f}
  sed -i '/EMAIL_PORT.*/d' ${f}
  sed -i '/DEFAULT_FROM_EMAIL.*/d' ${f}
  sed -i '/SERVER_EMAIL.*/d' ${f}

  email_host=`grep -w seafile/email_host /etc/univention/base.conf | sed "s|seafile/email_host:||" | tr -d '[:space:]'`
  if [[ ! $email_host == "" ]]; then
    email_host_password=`grep seafile/email_host_password /etc/univention/base.conf | sed "s|seafile/email_host_password:||" | tr -d '[:space:]'`
    email_host_port=`grep seafile/email_host_port /etc/univention/base.conf | sed "s|seafile/email_host_port:||" | tr -d '[:space:]'`
    email_host_user=`grep seafile/email_host_user /etc/univention/base.conf | sed "s|seafile/email_host_user:||" | tr -d '[:space:]'`
    email_use_tls=`grep seafile/email_use_tls /etc/univention/base.conf | sed "s|seafile/email_use_tls:||" | tr -d '[:space:]'`
    if [[ $email_use_tls == "true" ]]; then
      email_use_tls="True"
    elif [[ $email_use_tls == "false" ]]; then
      email_use_tls="False"
    fi
    echo "
EMAIL_USE_TLS = "$email_use_tls"
EMAIL_HOST = '"$email_host"'
EMAIL_HOST_USER = '"$email_host_user"'
EMAIL_HOST_PASSWORD = '"$email_host_password"'
EMAIL_PORT = "$email_host_port"
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
SERVER_EMAIL = EMAIL_HOST_USER" >> ${f}
  fi
}

function generate_nginx_configs () {
  # diese Funktion wird immer (d.h. bei Install & Update) ausgeführt
  # die nginx-Konfiguration wird immer überschrieben und das mitgelieferte template wird nicht genutzt
  rm /etc/nginx/conf.d/*
  sed -e '/sites-enabled/ s/^#*/#/' -i /etc/nginx/nginx.conf

  # write new config
  f="/etc/nginx/conf.d/seafile.conf"
  echo '
  server {
    listen 80;
    server_name _;
    error_page 502 403 404 /error.html;
    location = /error.html {
      root /var/www;
    }
    location / {
      proxy_pass http://127.0.0.1:8000/;
      proxy_read_timeout 300s;
      proxy_set_header Host $host;
      proxy_set_header Forwarded "for=$proxy_add_x_forwarded_for;proto=$http_x_forwarded_proto";
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
      proxy_set_header X-Real-IP $proxy_add_x_forwarded_for;
      proxy_set_header Connection "";
      proxy_http_version 1.1;
      client_max_body_size 0;
      access_log /var/log/nginx/seahub.access.log seafileformat;
      error_log /var/log/nginx/seahub.error.log;
    }
    location /seafile/seafhttp {
      rewrite ^/seafile/seafhttp(.*)$ $1 break;
      proxy_pass http://127.0.0.1:8082;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      client_max_body_size 0;
      proxy_connect_timeout  36000s;
      proxy_read_timeout  36000s;
      proxy_request_buffering off;
      access_log /var/log/nginx/seafhttp.access.log seafileformat;
      error_log /var/log/nginx/seafhttp.error.log;
    }
    location /seafile/seafdav {
      client_max_body_size 0;
      proxy_pass http://127.0.0.1:8080;
      proxy_set_header Host $host;
      proxy_set_header Forwarded "for=$proxy_add_x_forwarded_for;proto=$http_x_forwarded_proto";
      proxy_set_header X-Real-IP $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
      proxy_connect_timeout 1200s;
      proxy_read_timeout 1200s;
      proxy_send_timeout 1200s;
      send_timeout 1200s;
      proxy_request_buffering off;
      access_log /var/log/nginx/seafdav.access.log seafileformat;
      error_log /var/log/nginx/seafdav.error.log;
    }
    location /seafile/seafmedia {
      rewrite ^/seafile/seafmedia(.*)$ /media$1 break;
      root /opt/seafile/seafile-server-latest/seahub;
    }
  }' > ${f}
  nginx -s reload
}

function remove_pw_forgot(){
  f="/opt/seafile/seafile-server-latest/seahub/seahub/templates/registration/login.html"
  sed -i '/forgot-passwd.*/d' ${f}
}

function restart_seafile(){
  /opt/seafile/seafile-server-latest/seahub.sh stop
  /opt/seafile/seafile-server-latest/seafile.sh stop
  sleep 1
  /opt/seafile/seafile-server-latest/seafile.sh start
  /opt/seafile/seafile-server-latest/seahub.sh start
}

function wait_until_container_ready(){
  timeout=120
  while [[ ! -f /opt/seafile/conf/seahub_settings.py || ! -f /opt/seafile/conf/ccnet.conf ]]; 
  do
    if [ "$timeout" == 0 ]; then
      echo "ERROR: seafile container is not ready..."
      exit 1
    fi
    ((timeout--))
    sleep 1
  done
}

function generate_nginx_error_page(){
  echo '<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Seafile | Reload/Error-Page</title>
	<link href="https://fonts.googleapis.com/css?family=Cabin:400,700" rel="stylesheet">
	<link href="https://fonts.googleapis.com/css?family=Montserrat:900" rel="stylesheet">
	<style>
	*{-webkit-box-sizing:border-box;box-sizing:border-box}body{padding:0;margin:0}#notfound{position:relative;height:100vh}#notfound .notfound{position:absolute;left:50%;top:50%;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.notfound{max-width:520px;width:90%;line-height:1.4;text-align:center}.notfound .notfound-404{position:relative;height:240px}.notfound .notfound-404 h1{font-family:Montserrat,sans-serif;position:absolute;left:50%;top:50%;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%);font-size:252px;font-weight:900;margin:0;color:#262626;text-transform:uppercase;letter-spacing:-40px;margin-left:-20px}.notfound .notfound-404 h1>span{text-shadow:-8px 0 0 #fff}.notfound .notfound-404 h3{font-family:Cabin,sans-serif;position:relative;font-size:16px;font-weight:700;text-transform:uppercase;color:#262626;margin:0;letter-spacing:3px;padding-left:6px}.notfound h2{font-family:Cabin,sans-serif;font-size:16px;font-weight:400;text-transform:uppercase;color:#000;margin-top:0;margin-bottom:25px}
	@media only screen and (max-width:767px){.notfound .notfound-404{height:200px}.notfound .notfound-404 h1{font-size:200px}}
	@media only screen and (max-width:480px){.notfound .notfound-404{height:200px}.notfound .notfound-404 h1{font-size:162px;height:150px;line-height:162px}.notfound h2{font-size:12px}}
	</style>
</head>

<body>
	<div id="notfound">
		<div class="notfound">
			<div class="notfound-404">
				<h3>Oops! Seafile does not respond</h3>
				<h1><span>5</span><span>0</span><span>2</span></h1>
			</div>
			<h2>Seafile does not answer. Maybe the service is just restarting. Please reload the page in some seconds. Otherwise try to restart the container or check the univention logs.</h2>
		</div>
	</div>
</body>
</html>' > /var/www/error.html
}

###############################################
###############################################

if [[ $1 == "install" ]]; then
  echo $(date +%c): configure - install
  wait_until_container_ready
  generate_nginx_configs
  generate_nginx_error_page
  init_ldap
  init_seahub
  remove_pw_forgot
  restart_seafile
fi

if [[ $1 == "settings" ]]; then
  update_seafdav
  update_email
  remove_pw_forgot
  restart_seafile
fi

if [[ $1 == "upgrade" ]]; then
  echo $(date +%c): configure - upgrade
  wait_until_container_ready
  remove_pw_forgot
  generate_nginx_configs
  generate_nginx_error_page
  restart_seafile
fi

exit 0