#!/usr/bin/env bash
#
# Copyright (c) 2026 Canaima_Deploy Contributors
#
# This file is part of Canaima_Deploy (see https://canaima_deploy.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# Exit hook on subcommand error or unset variable
set -eu

base_folder_and_perm_init() {

    #############################
    # Base canaima_deploy conf folder #
    #############################

    mkdir -p /etc/canaima_deploy
    # NB: x permission for 'others' is important for ssl-cert (and maybe mdns), otherwise slapd will fail to start because can't access the certs
    chmod 755 /etc/canaima_deploy

    ################
    # Logs folders #
    ################

    mkdir -p /var/log/canaima_deploy
    chown root:root /var/log/canaima_deploy
    chmod 750 /var/log/canaima_deploy

    ##################
    # Portal folders #
    ##################

    getent passwd ynh-portal &> /dev/null || useradd --no-create-home --shell /usr/sbin/nologin --system --user-group ynh-portal

    mkdir -p /etc/canaima_deploy/portal
    chmod 500 /etc/canaima_deploy/portal
    chown ynh-portal:ynh-portal /etc/canaima_deploy/portal

    mkdir -p /usr/share/canaima_deploy/portal/customassets
    chmod 775 /usr/share/canaima_deploy/portal/customassets
    chown root:root /usr/share/canaima_deploy/portal/customassets

    touch /var/log/canaima_deploy-portalapi.log
    chown ynh-portal:root /var/log/canaima_deploy-portalapi.log
    chmod 600 /var/log/canaima_deploy-portalapi.log

    ###############################
    # Sessions folder and secrets #
    ###############################

    # Portal
    mkdir -p /var/cache/canaima_deploy-portal/sessions
    chown ynh-portal:www-data /var/cache/canaima_deploy-portal
    chmod 510 /var/cache/canaima_deploy-portal
    chown ynh-portal:www-data /var/cache/canaima_deploy-portal/sessions
    chmod 710 /var/cache/canaima_deploy-portal/sessions

    # Webadmin
    mkdir -p /var/cache/canaima_deploy/sessions
    chown root:root /var/cache/canaima_deploy/sessions
    chmod 700 /var/cache/canaima_deploy/sessions

    if test -e /etc/canaima_deploy/installed; then
        # Initialize session secrets
        # Obviously we only do this in the post_regen, ie during the postinstall, because we don't want every pre-installed instance to have the same secret
        if [ ! -e /etc/canaima_deploy/.admin_cookie_secret ]; then
            dd if=/dev/urandom bs=1 count=1000 2> /dev/null | tr --complement --delete 'A-Za-z0-9' | head -c 64 > /etc/canaima_deploy/.admin_cookie_secret
        fi
        chown root:root /etc/canaima_deploy/.admin_cookie_secret
        chmod 400 /etc/canaima_deploy/.admin_cookie_secret

        if [ ! -e /etc/canaima_deploy/.ssowat_cookie_secret ]; then
            # NB: we need this to be exactly 32 char long, because it is later used as a key for AES256
            dd if=/dev/urandom bs=1 count=1000 2> /dev/null | tr --complement --delete 'A-Za-z0-9' | head -c 32 > /etc/canaima_deploy/.ssowat_cookie_secret
        fi
        chown ynh-portal:root /etc/canaima_deploy/.ssowat_cookie_secret
        chmod 400 /etc/canaima_deploy/.ssowat_cookie_secret
    fi

    ##################
    # Domain folders #
    ##################

    mkdir -p /etc/canaima_deploy/domains
    chown root /etc/canaima_deploy/domains
    chmod 700 /etc/canaima_deploy/domains

    ###############
    # App folders #
    ###############

    mkdir -p /etc/canaima_deploy/apps
    chown root /etc/canaima_deploy/apps
    chmod 700 /etc/canaima_deploy/apps

    #####################
    # Apps data folders #
    #####################

    mkdir -p /home/canaima_deploy.app
    chmod 755 /home/canaima_deploy.app

    ################
    # Certs folder #
    ################

    mkdir -p /etc/canaima_deploy/certs
    chown -R root:ssl-cert /etc/canaima_deploy/certs
    chmod 750 /etc/canaima_deploy/certs
    # We do this with find because there could be a lot of them...
    find /etc/canaima_deploy/certs/ -type f -exec chmod 640 {} \;
    find /etc/canaima_deploy/certs/ -type d -exec chmod 750 {} \;

    ##################
    # Backup folders #
    ##################

    mkdir -p /home/canaima_deploy.backup/archives
    chmod 770 /home/canaima_deploy.backup
    chmod 770 /home/canaima_deploy.backup/archives

    if test -e /etc/canaima_deploy/installed; then
        # The admins group only exist after the postinstall
        getent group admins >/dev/null && chown root:admins /home/canaima_deploy.backup || true
        getent group admins >/dev/null && chown root:admins /home/canaima_deploy.backup/archives || true
    else
        chown root:root /home/canaima_deploy.backup
        chown root:root /home/canaima_deploy.backup/archives
    fi

    ########
    # Misc #
    ########

    mkdir -p /etc/canaima_deploy/hooks.d
    chown root /etc/canaima_deploy/hooks.d
    chmod 700 /etc/canaima_deploy/hooks.d

    mkdir -p /var/cache/canaima_deploy/repo
    chown root:root /var/cache/canaima_deploy
    chmod 700 /var/cache/canaima_deploy

    [ ! -e /var/www/.well-known/ynh-diagnosis/ ] || chmod 775 /var/www/.well-known/ynh-diagnosis/

    if test -e /etc/canaima_deploy/installed; then
        # We use "|| true" because some filesystem do not support ACL (such as NTFS)
        setfacl -m g:all_users:--- /var/www &>/dev/null || true
        setfacl -m g:all_users:--- /var/log/nginx &>/dev/null || true
        setfacl -m g:all_users:--- /etc/canaima_deploy &>/dev/null || true
        setfacl -m g:all_users:--- /etc/canaima-ssowat &>/dev/null || true
    fi
}

do_init_regen() {

    cd /usr/share/canaima_deploy/conf/canaima_deploy

    # Asegurar la creación física del nuevo directorio antes de escribir en él
    mkdir -p /etc/canaima-ssowat

    base_folder_and_perm_init

    # Empty ssowat json persistent conf (Apuntando a la ruta soberana corregida)
    echo "{}" > '/etc/canaima-ssowat/conf.json.persistent'
    chmod 644 /etc/canaima-ssowat/conf.json.persistent
    chown root:root /etc/canaima-ssowat/conf.json.persistent
    echo "{}" > '/etc/canaima-ssowat/conf.json'
    chmod 644 /etc/canaima-ssowat/conf.json
    chown root:root /etc/canaima-ssowat/conf.json

    # Empty service conf
    touch /etc/canaima_deploy/services.yml

    # set default current_host
    [[ -f /etc/canaima_deploy/current_host ]] \
        || echo "canaima_deploy.org" > /etc/canaima_deploy/current_host

    # copy default services and firewall
    [[ -f /etc/canaima_deploy/firewall.yml ]] \
        || cp firewall.yml /etc/canaima_deploy/firewall.yml

    # allow users to access /media directory
    [[ -d /etc/skel/media ]] \
        || (mkdir -p /media && ln -s /media /etc/skel/media)

    # Canaima_Deploy services (Corregidos con guion medio de acuerdo al disco)
    cp canaima_deploy-api.service /etc/systemd/system/canaima_deploy-api.service
    cp canaima_deploy-portal-api.service /etc/systemd/system/canaima_deploy-portal-api.service
    cp canaima_deploy-prompt.service /etc/systemd/system/yunoprompt.service

    systemctl daemon-reload

    systemctl enable canaima_deploy-api.service --quiet
    systemctl start canaima_deploy-api.service

    systemctl enable canaima_deploy-portal-api.service --quiet
    systemctl start canaima_deploy-portal-api.service

    # Enable yunoprompt (in particular for installs from ISO)
    systemctl enable yunoprompt --quiet

    cp dpkg-origins /etc/dpkg/origins/canaima_deploy

    # Change dpkg vendor
    if readlink -f /etc/dpkg/origins/default | grep -q debian; then
        rm -f /etc/dpkg/origins/default
        ln -s /etc/dpkg/origins/canaima_deploy /etc/dpkg/origins/default
    fi
}

do_pre_regen() {
    pending_dir=$1

    cd /usr/share/canaima_deploy/conf/canaima_deploy

    mkdir -p "$pending_dir/etc/systemd/system"
    mkdir -p "$pending_dir/etc/cron.d/"
    mkdir -p "$pending_dir/etc/cron.daily/"

    # add cron job for diagnosis
    cat > "$pending_dir/etc/cron.d/canaima_deploy-diagnosis" << EOF
SHELL=/bin/bash
0 7,19 * * * root : Canaima_Deploy Automatic Diagnosis; sleep \$((RANDOM\\%1200)); canaima_deploy diagnosis run --email > /dev/null 2>/dev/null || echo "Running the automatic diagnosis failed miserably"
EOF

    # Cron job that upgrade the app list everyday
    cat > "$pending_dir/etc/cron.daily/canaima_deploy-fetch-apps-catalog" << EOF
#!/bin/bash
sleep \$((RANDOM%3600)); canaima_deploy tools update apps > /dev/null
EOF

    # Cron job that renew lets encrypt certificates
    cat > "$pending_dir/etc/cron.daily/canaima_deploy-certificate-renew" << EOF
#!/bin/bash
canaima_deploy domain cert renew --email
EOF

    # If we subscribed to a dyndns domain, add the corresponding cron
    if ls -l /etc/canaima_deploy/dyndns/K*.key 2> /dev/null; then
        cat > "$pending_dir/etc/cron.d/canaima_deploy-dyndns" << EOF
SHELL=/bin/bash
*/10 * * * * root : Canaima_Deploy DynDNS update; sleep \$((RANDOM\\%60)); ! ping -q -W5 -c1 ipv4.canaima_deploy.org >/dev/null 2>&1 || test -e /var/run/moulinette_canaima_deploy.lock || canaima_deploy dyndns update >> /dev/null
EOF
    else
        touch "$pending_dir/etc/cron.d/canaima_deploy-dyndns"
    fi

    # Skip ntp if inside a container
    if systemctl | grep -q 'ntp.service'; then
        mkdir -p "$pending_dir/etc/systemd/system/ntp.service.d/"
        cat > "$pending_dir/etc/systemd/system/ntp.service.d/ynh-override.conf" << EOF
[Unit]
ConditionCapability=CAP_SYS_TIME
ConditionVirtualization=!container
EOF
    fi

    mkdir -p "$pending_dir/etc/systemd/system/nftables.service.d/"
    cp canaima_deploy-nftables-hooks-override.conf "$pending_dir/etc/systemd/system/nftables.service.d/canaima_deploy-nftables-hooks.conf"
    touch "$pending_dir/etc/systemd/system/nftables.service.d/ynh-override.conf"

    # Don't suspend computer on LidSwitch
    mkdir -p "$pending_dir/etc/systemd/logind.conf.d/"
    cat > "$pending_dir/etc/systemd/logind.conf.d/ynh-override.conf" << EOF
[Login]
HandleLidSwitch=ignore
HandleLidSwitchDocked=ignore
HandleLidSwitchExternalPower=ignore
EOF

    # Sincronizados con guiones medios para evitar fallos de stat
    cp canaima_deploy-api.service "$pending_dir/etc/systemd/system/canaima_deploy-api.service"
    cp canaima_deploy-portal-api.service "$pending_dir/etc/systemd/system/canaima_deploy-portal-api.service"
    cp canaima_deploy-prompt.service "$pending_dir/etc/systemd/system/yunoprompt.service"
    cp proc-hidepid.service "$pending_dir/etc/systemd/system/proc-hidepid.service"
    touch "$pending_dir/etc/systemd/system/canaima_deploy-firewall.service"

    mkdir -p "$pending_dir/etc/dpkg/origins/"
    cp dpkg-origins "$pending_dir/etc/dpkg/origins/canaima_deploy"

    touch "$pending_dir/etc/cron.daily/node_update"
}

do_post_regen() {
    regen_conf_files=$1

    base_folder_and_perm_init

    if [ ! -e /var/log/canaima_deploy/operations ]; then
        mkdir -p /var/log/canaima_deploy/operations
    fi
    if [ -d /var/log/canaima_deploy/categories/operation ] && [ ! -L /var/log/canaima_deploy/categories/operation ]; then
        find /var/log/canaima_deploy/categories/operation/ -type f -print0 | xargs -0 -I {} mv {} /var/log/canaima_deploy/operations/
        rmdir /var/log/canaima_deploy/categories/operation || mv /var/log/canaima_deploy/categories/operation /var/log/canaima_deploy/categories/operation.old
        ln -s /var/log/canaima_deploy/operations /var/log/canaima_deploy/categories/operation
    fi

    find /etc/systemd/system/*.service -type f | xargs -r chown root:root
    find /etc/systemd/system/*.service -type f | xargs -r chmod 0644

    if ls -l /etc/php/*/fpm/pool.d/*.conf 2> /dev/null; then
        chown root:root /etc/php/*/fpm/pool.d/*.conf
        chmod 644 /etc/php/*/fpm/pool.d/*.conf
    fi

    find /etc/cron.*/canaima_deploy-* -type f -exec chmod 755 {} \;
    find /etc/cron.d/canaima_deploy-* -type f -exec chmod 644 {} \;
    find /etc/cron.*/canaima_deploy-* -type f -exec chown root:root {} \;

    for USER in $(canaima_deploy user list --quiet --output-as json | jq -r '.users | .[] | .username'); do
        [ ! -e "/home/$USER" ] || setfacl -m g:all_users:--- "/home/$USER" &>/dev/null || true
    done

    for file in /etc/canaima_deploy/{*.yml,*.yaml,*.json,mysql,psql}; do
        if [ -f "$file" ]; then
            if [ "$file" != "mdns.yml" ]; then
                chown root:root "$file"
            fi
            chmod 600 "$file"
        fi
    done

    grep -q '^ssh.app:' /etc/group || groupadd ssh.app
    grep -q '^sftp.app:' /etc/group || groupadd sftp.app

    if systemctl | grep -q 'ntp.service'; then
        [[ ! "$regen_conf_files" =~ "ntp.service.d/ynh-override.conf" ]] || {
            systemctl daemon-reload
            systemctl restart ntp
        }
    fi

    [[ ! "$regen_conf_files" =~ "login.conf.d/ynh-override.conf" ]] || {
        systemctl daemon-reload
        systemctl restart systemd-logind
    }
    # Corregidos nombres de servicio con guion medio para recargas de Systemd
    [[ ! "$regen_conf_files" =~ "canaima_deploy-api.service" ]] || systemctl daemon-reload
    [[ ! "$regen_conf_files" =~ "canaima_deploy-portal-api.service" ]] || systemctl daemon-reload
    [[ ! "$regen_conf_files" =~ "nftables.service.d/canaima_deploy-nftables-hooks.conf" ]] || systemctl daemon-reload

    if [[ "$regen_conf_files" =~ "yunoprompt.service" ]]; then
        systemctl daemon-reload
        action=$([[ -e /etc/systemd/system/yunoprompt.service ]] && echo 'enable' || echo 'disable')
        systemctl "$action" yunoprompt --quiet --now
    fi
    if [[ "$regen_conf_files" =~ "proc-hidepid.service" ]]; then
        systemctl daemon-reload
        action=$([[ -e /etc/systemd/system/proc-hidepid.service ]] && echo 'enable' || echo 'disable')
        systemctl "$action" proc-hidepid --quiet --now
    fi

    systemctl enable canaima_deploy-portal-api.service --quiet
    systemctl is-active canaima_deploy-portal-api --quiet || systemctl start canaima_deploy-portal-api.service

    if readlink -f /etc/dpkg/origins/default | grep -q debian; then
        rm -f /etc/dpkg/origins/default
        ln -s /etc/dpkg/origins/canaima_deploy /etc/dpkg/origins/default
    fi

    if test -e /etc/canaima_deploy/installed && test -e /etc/profile.d/check_canaima_deploy_is_installed.sh; then
        rm /etc/profile.d/check_canaima_deploy_is_installed.sh
    fi
}

"do_$1_regen" "$(echo "${*:2}" | xargs)"