#!/bin/bash

set -e

generate_config() {
COOKIE_SECRET=$(openssl rand -hex 32)
cat << EOF > jupyterhub_config.py
import os
import sys

# Use SystemdSpawner instead of the default LocalProcessSpawner
# c.JupyterHub.spawner_class = 'systemdspawner.SystemdSpawner'
# c.SystemdSpawner.default_shell = '/bin/bash'
# c.SystemdSpawner.unit_extra_properties = {'LimitMEMLOCK': 'infinity'}

# Use JupyterLab by default
c.Spawner.default_url = '/lab'

# PAMAuthenticator configs
c.PAMAuthenticator.open_sessions = False
c.PAMAuthenticator.pam_normalize_username = True

# Stop/cull idle JupyterHub processes
c.JupyterHub.services = [
    {
        'name': 'idle-culler',
        'admin': True,
        'command': [
            sys.executable,
            '-m', 'jupyterhub_idle_culler',
            '--timeout=3600'
        ],
    }
]

# JupyterHub autogenerated files
c.JupyterHub.cookie_secret = bytes.fromhex('$COOKIE_SECRET')
c.JupyterHub.db_url = f'{os.getcwd()}/jupyterhub.sqlite'
c.ConfigurableHTTPProxy.pid_file = f'{os.getcwd()}/jupyterhub-proxy.pid'

# Set the log level by value or name.
c.JupyterHub.log_level = 'DEBUG'

# Enable debug-logging of the single-user server
c.Spawner.debug = True
c.LocalProcessSpawner.debug = True

# JupyterHub Authenticator
AUTH_TYPE = os.getenv('AUTH_TYPE')
if AUTH_TYPE in ('freeipa', 'openldap'):
    # LDAP Authenticator
    c.JupyterHub.authenticator_class = 'ldapauthenticator.LDAPAuthenticator'
    c.LDAPAuthenticator.server_hosts = os.getenv('LDAP_SERVER_HOST').split(',')
    c.LDAPAuthenticator.bind_user_dn = os.getenv('LDAP_BIND_USER_DN')
    c.LDAPAuthenticator.bind_user_password = os.getenv('LDAP_BIND_USER_PASSWORD')
    c.LDAPAuthenticator.user_search_base = os.getenv('LDAP_USER_SEARCH_BASE')
    c.LDAPAuthenticator.user_search_filter = os.getenv('LDAP_USER_SEARCH_FILTER')
    c.LDAPAuthenticator.create_user_home_dir = True
    c.LDAPAuthenticator.create_user_home_dir_cmd = ['mkhomedir_helper']
    if AUTH_TYPE == 'freeipa':
        c.LDAPAuthenticator.user_membership_attribute = 'memberOf'
    else:
        c.LDAPAuthenticator.username_pattern = '[a-zA-Z0-9_.][a-zA-Z0-9_.-]{0,252}[a-zA-Z0-9_.hB]?'
EOF
echo "Configuration file generated: `pwd`/jupyterhub_config.py"
}

print_help () {
  echo ""
  echo "JupyterLab Workbench is an opensource software with pre-installed"
  echo "jupyterlab and essential packages intended for corporations, researchers,"
  echo "scientists, students, educators, and etc."
  echo ""
  echo "Usage:"
  echo ""
  echo "    jlwb [...options]"
  echo ""
  echo "Options:"
  echo ""
  echo "    start -f <config_file>    - Start the JupyterLab Workbench using the"
  echo "                                generated configuration file."
  echo "    generate_config           - Generate the JupyterHub configuration file. "
  echo ""
}

while [[ $# -gt 0 ]]; do
  case $1 in
    build)
      JUPYTER=`which jupyter`
      $JUPYTER lab build
      shift
      ;;
    start)
      case $2 in
        -f|--file)
          CURRENT_DIR=`pwd`
          FILE=$CURRENT_DIR/$3
          JUPYTERHUB=`which jupyterhub`
          if [[ -f $FILE ]]; then
            $JUPYTERHUB -f $FILE
          else
            echo "Configuration file does not exist, you can generate by using 'generate_config' option."
          fi
          shift
          ;;
        *)
          print_help
          exit 1
      esac
      ;;
    generate_config)
      if [[ -f "`pwd`/jupyterhub_config.py" ]]
      then
        while true; do
          read -p "Configuration file already exists. Do you want to overwrite existing file? (yes/no) " yn
          case $yn in
            Yes|y|yes) generate_config; exit;;
            No|n|no) exit;;
            *) echo "Please answer 'Yes'|'yes'|'y' or 'No'|'no'|'n'.";;
          esac
        done
      fi
      generate_config
      shift
      ;;
    help)
      print_help
      shift
      ;;
    *)
      echo "Run 'jlwb help' for more information on a command."
      exit 1
  esac
done
