#!/bin/bash
#
# postinst script for linuxmuster-api7
# GPL v3
#

set -e

# Hide root warning for pip
export PIP_ROOT_USER_ACTION=ignore
export PIP_BREAK_SYSTEM_PACKAGES=1

msg()
{
    message=$1
    echo
    # Bold and orange font for linuxmuster.net
    echo -e "\e[1m\e[38;5;214m$message\e[39m\e[0m"
    echo
}

create_linuxmuster_venv()
{
    msg "Setting up virtual env in /opt"
    /usr/bin/python3 -m venv /opt/linuxmuster --system-site-packages
}

migrate_to_venv()
{
    # Checking if the linuxmuster's venv is already installed
    if [ -f /opt/linuxmuster/bin/activate ] ; then
      return
    fi

    create_linuxmuster_venv
}

case "$1" in
    install|configure)
        msg "Install Python requirements"
        
        migrate_to_venv
        . /opt/linuxmuster/bin/activate
        
        PYTHON3=/opt/linuxmuster/bin/python3
        
        $PYTHON3 -m pip install -r /usr/lib/python3/dist-packages/linuxmusterApi/requirements.txt

        msg "Checking config files"
        if [ ! -f "/etc/linuxmuster/api/config.yml" ] ; then
            mkdir -p /etc/linuxmuster/api
            SECRET_KEY=$(openssl rand 64 | openssl enc -A -base64)
            cat << EOF > /etc/linuxmuster/api/config.yml
uvicorn:
  port: 8001
  host: 0.0.0.0
  ssl_certfile: /etc/linuxmuster/api/lmnapi.pem
  ssl_keyfile: /etc/linuxmuster/api/lmnapi.pem
  log_level: info
  log_config: /etc/linuxmuster/api/uvicorn_log_conf.yml
secret: $SECRET_KEY
EOF
        fi

        chmod 600 /etc/linuxmuster/api/config.yml

        msg "Checking log files"
        mkdir -p /var/log/linuxmuster/api
        cp /usr/lib/python3/dist-packages/linuxmusterApi/templates/uvicorn_log_conf.yml /etc/linuxmuster/api/uvicorn_log_conf.yml

        # For sophomorix users' commands logs
        mkdir -p /tmp/lmnapi
        chmod 600 /tmp/lmnapi

        msg "Checking certificate"
        if [ ! -f "/etc/linuxmuster/api/lmnapi.pem" ] ; then
            /usr/lib/python3/dist-packages/linuxmusterApi/scripts/lmnapi-ssl-gen.py
        fi

        msg "Reload service linuxmuster-api"
        systemctl enable linuxmuster-api
        systemctl daemon-reload
        systemctl restart linuxmuster-api

    ;;

    *)
    ;;

esac

exit 0
