#!/bin/bash

set -x

echo "Setup script is running..."

TZ="$(cat /etc/timezone)"
export TZ
ln -snf "/usr/share/zoneinfo/${TZ}" /etc/localtime
touch /usr/local/filewave/tmp/TIMEZONE_SET

echo "date in setup script: $(date)"

#
# Initialize just the first time
#
if ! [[ -d /usr/local/filewave/fwxserver/DB/pg_data ]]; then

  echo "First time setup..."

  /etc/init.d/fw-server stop
  dpkg --unpack /install/fwxserver*.deb
  apt install -y --reinstall /install/fwxserver*.deb
  /etc/init.d/fw-server stop

  # Set inventory preferences
  /usr/local/filewave/python/bin/python - <<'EOF'
import os
import sys
import uuid


from django.core.wsgi import get_wsgi_application

# derive location to your django project setting.py
proj_path = os.path.split(os.path.abspath(os.path.dirname('/usr/local/filewave/django/filewave/settings.py')))[0]
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "filewave.settings")
sys.path.append(proj_path)

# load your settings.py
os.chdir(proj_path)
application = get_wsgi_application()


from fwauth.models.user import AppToken
from fwserver.models import Preferences
from fwserver.name_value_pair import (
    get_inventory_server_configuration,
    get_mdm_server_configuration,
    set_inventory_server_configuration,
    set_mdm_server_configuration,
)
from ios.preferences_manager import PreferencesManager

print("inventory_configurator.py: started modifications")
mdm_conf = get_mdm_server_configuration()
if not mdm_conf.ListFields():
    # Get the host name from UCS
    host = os.environ.get('SERVER_HOSTNAME')
    # Generate new MDM shared key
    mdm_shared_key = '{%s}' % uuid.uuid4()
    PreferencesManager.set_shared_key(mdm_shared_key)
    PreferencesManager.set_mdm_cert_trusted(True)

    # Also set default values for MDM configuration of fwxserver
    mdm_conf.host = host
    mdm_conf.admin_ssl_port = 20445
    mdm_conf.shared_secret = mdm_shared_key
    mdm_conf.inventory_interval = 24
    mdm_conf.smart_group_inventory_refresh_period = 10
    mdm_conf.inventory_clear_ldap_custom_field_if_no_match = False
    set_mdm_server_configuration(mdm_conf)

    # fwxserver needs to have the Preferences set to read the shared keys from the MDM config
    # But the `mdm_shared_secret` field is not used from Preferences
    Preferences.objects.get_or_create(
        id=1,
        defaults={
            'ldap_auth_server': 0,
            'extract_from_ldap_auth': 0,
        }
    )

    # Set inventory configuration of fwxserver
    inv_conf = get_inventory_server_configuration()
    inv_conf.host = host
    inv_conf.server_ssl_port = 20445
    # The inventory shared key (which is now the default app token of the superuser)
    # is available even on the first run
    inv_conf.shared_secret = AppToken.objects.filter(user__is_superuser=True, is_default=True).first().token
    set_inventory_server_configuration(inv_conf)
EOF

  # Start FW Server
  /etc/init.d/fw-server start

  # Model update
  /usr/local/filewave/python/bin/python - <<'EOF'
import os
import sys
import time
from functools import wraps
import requests
import urllib3


WEBADMIN_HOST = 'localhost:4443'
WEBADMIN_USER = 'fwadmin'
WEBADMIN_PASS = 'filewave'
LOGIN_ENDPOINT = 'https://{}/api/auth/login'.format(WEBADMIN_HOST)
MODEL_INFO_ENDPOINT = 'https://{}/api/fwserver/model_info'.format(WEBADMIN_HOST)
MODEL_UPDATE_ENDPOINT = 'https://{}/api/fwserver/update_model'.format(WEBADMIN_HOST)
HEADERS = {'referer': 'https://localhost:4443'}
POLL_STEPS_NUM = 30     # number of polling turns
POLL_STEP_SLEEP = 10    # one polling turn duration


def retry_if_exception(ex, max_retries):
    def outer(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            assert max_retries > 0
            x = max_retries
            while x:
                try:
                    return func(*args, **kwargs)
                except ex as e:
                    x -= 1
                    print(f'Failed with exception: {repr(e)}')
                    print(f'There will be {x} more retries...')
                    time.sleep(POLL_STEP_SLEEP)
            raise AllRetriesFailedException
        return wrapper
    return outer


class ModelUpdateNumberNotIncreasedException(Exception):
    """This exception is thrown when model update check indicate that model number check did not increase."""


class ModelUpdateStatusNotNoneException(Exception):
    """This exception is thrown when model update check indicate that model update is in progress."""


class AllRetriesFailedException(Exception):
    """This exception is thrown when retry decorator exhaust retires."""


@retry_if_exception((requests.HTTPError, requests.exceptions.ConnectionError,), POLL_STEPS_NUM)
def do_model_update():
    with requests.Session() as session:
        print('Authenticating...')
        login_request = session.post(LOGIN_ENDPOINT, verify=False, headers=HEADERS, json={'username': WEBADMIN_USER,
                                                                                          'password': WEBADMIN_PASS})
        login_request.raise_for_status()

        print('About to get model information (before model update)...')
        check_request = session.get(MODEL_INFO_ENDPOINT, verify=False, headers=HEADERS)
        check_request.raise_for_status()
        check_request_json = check_request.json()
        print(f'Current model information: {check_request_json}')

        print('Executing model update...')
        update_request = session.post(MODEL_UPDATE_ENDPOINT, verify=False, headers=HEADERS)
        update_request.raise_for_status()

        return check_request_json


@retry_if_exception((ModelUpdateNumberNotIncreasedException, ModelUpdateStatusNotNoneException), POLL_STEPS_NUM)
def check_model_update(check_request_json):
    with requests.Session() as session:
        print('Authenticating...')
        login_request = session.post(LOGIN_ENDPOINT, verify=False, headers=HEADERS, json={'username': WEBADMIN_USER,
                                                                                          'password': WEBADMIN_PASS})
        login_request.raise_for_status()

        print('About to get model information (after model update)...')
        dblcheck_request = session.get(MODEL_INFO_ENDPOINT, verify=False, headers=HEADERS)
        dblcheck_request.raise_for_status()
        dblcheck_request_json = dblcheck_request.json()
        print(f'Current model information: {dblcheck_request_json}')

        if dblcheck_request_json['model_number'] <= check_request_json['model_number']:
            raise ModelUpdateNumberNotIncreasedException

        if dblcheck_request_json['model_update_status'] is not None:
            raise ModelUpdateStatusNotNoneException


# Disable warnings about unverified requests to localhost
urllib3.disable_warnings()

check_request_json = do_model_update()
check_model_update(check_request_json)
EOF

else
  echo "Intialization already completed."
fi