#!/bin/bash
#
#Server-Manager: o_web (Manages the web-server) [Power: 755]
#
#Version: 1.7.1
#Date:    2026.10.03
#Unix:    Debian 12
#Author:  P.Klapp
#Company: Omoti UG (haftungsbeschränkt)
#Website: https://omoti.de
#
#Path:    /Commands/

#Version
    version=$(awk '$1 == "#Version:" { print $2; exit }' "$0")

#Parameters
    #missing parameter
        if [[ -z ${1} ]]
        then
            echo "Missing parameter! Please use -h for help."
            exit 1
        fi

    use_custom_certs=false

    while getopts ":a:cd:f:ghip:x:" option
    do
        case ${option} in
            a)  #add
                task='add'
                fqdn="${OPTARG}"
            ;;

            c)  #use custom certificates
                use_custom_certs=true
            ;;

            d)  #delete
                task='del'
                fqdn="${OPTARG}"
            ;;

            f)  #forwarding
                task='forward'
                fqdn="${OPTARG}"
                read -p 'Destination link: ' link
            ;;

            g)  #git sync
                task='git'
            ;;

            h)  #help
                echo ''
                echo 'Usage: o_web OPTION...'
                echo "o_web (v${version}) Manages the web-server"
                echo ''
                echo 'Options:'
                echo '-a <fqdn>                 Adds a new website'
                echo '-c                        Use custom certificates from /srv/omoti/keys/web/ instead of certbot'
                echo '-d <fqdn>                 Deletes a website'
                echo '-f <fqdn>                 Adds a forwarding'
                echo '-g                        Performs a git sync'
                echo '-h                        Display this help and exit'
                echo '-i                        Install web server'
                echo '-p <fqdn>                 Parks a domain'
                echo '-x <fqdn>                 Adds a proxy'
                echo ''
                echo 'Further documentation can be found in the Omoti Wiki'
                echo 'https://gitlab.omoti.work/omoti/Server-Manager/-/wikis/home'
                echo ''
                exit 0
            ;;

            i)  #installation
                task='setup'
            ;;

            p)  #parking
                task='park'
                fqdn="${OPTARG}"
            ;;

            x)  #proxy
                task='proxy'
                fqdn="${OPTARG}"
                read -p 'Proxy destination URL (e.g., http://127.0.0.1:3000): ' proxy_link
            ;;

            \?) #invalid option
                echo "Invalid option! Please use -h for help."
                exit 1
            ;;

            :)  #missing argument
                echo "Missing argument! Please use -h for help."
                exit 1
            ;;
        esac
    done
    unset option

    if [[ ${use_custom_certs} == true ]]
    then
        cert_name=${fqdn%%.*}
    fi

#Functions
    apply_nginx_config() {
        local file="${1}"
        local target_file="/etc/nginx/sites-available/${fqdn}"

        ensureVhostLogFormat
        mv "${file}" "${target_file}"
        ln -s "${target_file}" /etc/nginx/sites-enabled/
        systemctl restart nginx
    }

    ensureVhostLogFormat () {
        local format_file='/etc/nginx/conf.d/vhost_logging.conf'

        if grep -REqs '^[[:space:]]*log_format[[:space:]]+vhost_combined([[:space:]]|$)' /etc/nginx/nginx.conf /etc/nginx/conf.d/
        then
            return
        fi

        cat > "${format_file}" <<'EOF'
log_format vhost_combined
    '$remote_addr - $host [$time_local] '
    '"$request" $status $body_bytes_sent '
    'server="$server_name" '
    'referer="$http_referer" '
    'ua="$http_user_agent" '
    'request_time=$request_time';
EOF
    }

    configureVhostLogging () {
        local site_name="${1}"
        local config_file="${2}"

        # The downloaded configs already contain these directives. This helper
        # covers additional Certbot blocks and the locally adapted default site.
        sed -i \
            -e '/^[[:space:]]*# o_web vhost logging$/,+2d' \
            -e '/^[[:space:]]*access_log[[:space:]][[:space:]]*off;[[:space:]]*$/d' \
            "${config_file}"

        sed -i "/^[[:space:]]*server[[:space:]]*{/a\\
    # o_web vhost logging\\
    access_log /var/log/nginx/${site_name}-access.log vhost_combined;\\
    error_log /var/log/nginx/${site_name}-error.log;" "${config_file}"
    }

    VersionAtLeast () {
        currentVersion=${1}
        requiredVersion=${2}

        if [[ -z ${currentVersion} ]] || [[ -z ${requiredVersion} ]]
        then
            return 1
        fi

        if [[ $(printf '%s\n%s\n' "${requiredVersion}" "${currentVersion}" | sort -V | head -n 1) == "${requiredVersion}" ]]
        then
            return 0
        fi

        return 1
    }

    SetDownloadMode () {
        downloadMode='legacy'
        omotiServerVersion=''

        if ! command -v omoti-server &> /dev/null
        then
            return
        fi

        if ! [[ -f /etc/omoti/credentials.json ]]
        then
            return
        fi

        omotiServerVersion=$(omoti-server -V 2> /dev/null)
        omotiServerVersion=${omotiServerVersion##* }

        if VersionAtLeast "${omotiServerVersion}" '0.7.0'
        then
            downloadMode='omoti-server'
        fi
    }

    DownloadFile () {
        source=${1}
        targetFile=${source##*/}
        downloadPath="/tmp/o_web.$(date +'%H%M%S')$(pwgen -s -0 -N 1 2).${targetFile}"

        #check parameter
            if [[ -z ${source} ]]
            then
                echo -e '\033[31mUnknown error!\033[0m Please check the log.'
                o_log -e 'Function DownloadFile: Missing parameter'
                exit 1
            fi

        if [[ ${downloadMode} == 'omoti-server' ]]
        then
            if ! omoti-server download --url "${source}" --path "${downloadPath}" --login &>> /srv/omoti/tmp/setup.log
            then
                echo -e "\033[31mFailed to download ${targetFile}\033[0m"
                o_log -e "Failed to download ${targetFile} via omoti-server"
                exit 1
            fi

            if ! [[ -f ${downloadPath} ]]
            then
                echo -e "\033[31mFailed to download ${targetFile}\033[0m"
                o_log -e "Downloaded file ${targetFile} is missing after omoti-server download"
                exit 1
            fi

            if ! mv "${downloadPath}" "${targetFile}"
            then
                echo -e "\033[31mFailed to move ${targetFile}\033[0m"
                o_log -e "Failed to move downloaded file ${targetFile} from /tmp"
                exit 1
            fi

        else
            o_download -a "${source}"
        fi
    }

    checkCertificates () {
        while [[ ! -f "/srv/omoti/keys/web/${cert_name}.key" ]] || [[ ! -f "/srv/omoti/keys/web/${cert_name}.crt" && ! -f "/srv/omoti/keys/web/${cert_name}.fullchain" ]]
        do
            echo "Waiting for SSL certificates to be placed in /srv/omoti/keys/web/ (${cert_name}.key and either ${cert_name}.crt or ${cert_name}.fullchain)..."
            sleep 10
        done
        echo "SSL certificates found."
    }

    deploy_nginx_site() {
        local config_file="${1}"
        local config_url="${2}"
        local extra_cmd="${3}"
        DownloadFile "${config_url}"
        sed -i "s/fqdn/${fqdn}/g" "${config_file}"
        if [[ -n "${extra_cmd}" ]]
        then
            eval "${extra_cmd}"
        fi
        apply_nginx_config "${config_file}"
    }

    dnsRecord () {
        echo
        echo 'The following DNS records must be set:'
        echo -e "${fqdn} -> \033[36m${ipv4}\033[0m"
        echo -e "${fqdn} -> \033[36m${ipv6}\033[0m"
        echo
        read -p 'Continue (y/n) [y]: ' controll
        echo

        controll=${controll:='y'}
        if [[ ${controll} != 'y' ]]
        then
            exit 1
        fi
    }

    enableHttps () {
        sed -i 's/listen 80;/listen 443 ssl;/g' /etc/nginx/sites-available/${fqdn}
        sed -i 's/listen [::]:80;/listen [::]:443 ssl;/g' /etc/nginx/sites-available/${fqdn}
        sed -i "s|server_name ${fqdn};|server_name ${fqdn};\n    ssl_certificate /srv/omoti/keys/web/${cert_name}.fullchain;\n    ssl_certificate_key /srv/omoti/keys/web/${cert_name}.key;\n    ssl_session_cache shared:SSL:10m;\n    ssl_protocols TLSv1.2 TLSv1.3;\n    ssl_ciphers \"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384\";\n    ssl_prefer_server_ciphers on;|g" /etc/nginx/sites-available/${fqdn}

        echo "" >> /etc/nginx/sites-available/${fqdn}
        echo "server {" >> /etc/nginx/sites-available/${fqdn}
        echo "    # o_web vhost logging" >> /etc/nginx/sites-available/${fqdn}
        echo "    access_log /var/log/nginx/${fqdn}-access.log vhost_combined;" >> /etc/nginx/sites-available/${fqdn}
        echo "    error_log /var/log/nginx/${fqdn}-error.log;" >> /etc/nginx/sites-available/${fqdn}
        echo "    listen 80;" >> /etc/nginx/sites-available/${fqdn}
        echo "    listen [::]:80;" >> /etc/nginx/sites-available/${fqdn}
        echo "    server_name ${fqdn};" >> /etc/nginx/sites-available/${fqdn}
        echo "" >> /etc/nginx/sites-available/${fqdn}
        echo "    return 301 https://\$host\$request_uri;" >> /etc/nginx/sites-available/${fqdn}
        echo "}" >> /etc/nginx/sites-available/${fqdn}
    }

    obtainCertbotCertificates () {
        certbot --nginx -m mail@omoti.de -n -d ${fqdn} --agree-tos
    }

    process_certificates() {
        if [[ "${use_custom_certs}" = true ]]
        then
             checkCertificates
             enableHttps
        else
             obtainCertbotCertificates
             configureVhostLogging "${fqdn}" "/etc/nginx/sites-available/${fqdn}"
        fi

        if ! nginx -t
        then
            echo -e '\033[31mThe nginx configuration is invalid\033[0m'
            exit 1
        fi

        nginx -s reload
    }

    verify_nginx_deployment() {
        if [[ -f /etc/nginx/sites-enabled/${fqdn} ]]
        then
            echo -e "\033[32mConfiguration for ${fqdn} is correctly deployed\033[0m"
        else
            echo -e "\033[31mConfiguration for ${fqdn} is missing\033[0m"
        fi
    }

#Dependencies
    #user
        user=${USER}
        user=${user:='System'}
        if [[ ${user} != 'root' ]] && [[ ${user} != 'System' ]]
        then
            echo
            echo -e "\033[33mThis command requests root rights\033[0m"
            echo 'Please run the command as root or with sudo!'
            echo
            exit 1
        fi
        unset user

#Variables
    #controll       -> Functions
    #currentVersion -> Functions/VersionAtLeast
    #downloadMode   -> Functions/SetDownloadMode
    #downloadPath   -> Functions/DownloadFile
    #fqdn           -> Parameters
    ipv0=$(hostname -I)
    ipv4=${ipv0%%\ *}
    ipv6=${ipv0#*\ }
    #link           -> Parameters/forwarding
    #omotiServerVersion -> Functions/SetDownloadMode
    #proxy_link     -> Parameters/proxy
    #requiredVersion -> Functions/VersionAtLeast
    #source         -> Functions/DownloadFile
    #option         -> Parameters
    #task           -> Parameters
    #targetFile     -> Functions/DownloadFile
    #user           -> Main/git sync
    #version        -> Version

#Preparation
    SetDownloadMode

#Main
    #add a new website
        if [[ ${task} == 'add' ]]
        then
            dnsRecord

            mkdir -p "/opt/${fqdn}/"
            deploy_nginx_site "web.cfg" "https://mgmt.omoti.de/Parts/Web/web.cfg"
            process_certificates
            verify_nginx_deployment "add"
        fi

    #deletes a website
        if [[ ${task} == 'del' ]]
        then
            if [[ -f /etc/nginx/sites-enabled/${fqdn} ]]
            then
                if [[ -d /opt/${fqdn}/ ]]
                then
                    rm -r -- "/opt/${fqdn}/"
                fi

                if [[ -f /etc/nginx/sites-enabled/${fqdn} ]]
                then
                    rm -- "/etc/nginx/sites-enabled/${fqdn}"
                fi

                if [[ -f /etc/nginx/sites-available/${fqdn} ]]
                then
                    rm -- "/etc/nginx/sites-available/${fqdn}"
                fi

                certbot delete -n --cert-name "${fqdn}"

                find /etc/letsencrypt/live/ -maxdepth 1 -name "${fqdn}*" -exec rm -r -- {} + 2> /dev/null
                find /etc/letsencrypt/archive/ -maxdepth 1 -name "${fqdn}*" -exec rm -r -- {} + 2> /dev/null
                find /etc/letsencrypt/renewal/ -maxdepth 1 -name "${fqdn}*" -exec rm -- {} + 2> /dev/null
                find /var/lib/letsencrypt/backups/ -maxdepth 1 -name "${fqdn}*" -exec rm -- {} + 2> /dev/null

                if [[ -d /opt/${fqdn}/ ]] || [[ -f /etc/nginx/sites-available/${fqdn} ]] || [[ -f /etc/nginx/sites-enabled/${fqdn} ]]
                then
                    echo -e "\033[31mAn error has occurred, please check the files manually\033[0m"
                    exit 1
                else
                    echo -e "\033[32mWebsite ${fqdn} was successfully deleted\033[0m"
                fi

            else
                echo -e "\033[33mThe specified website ${fqdn} does not exist\033[0m"
                exit 1
            fi
        fi

    #add a forwarding
        if [[ ${task} == 'forward' ]]
        then
            dnsRecord
            deploy_nginx_site "forwarding.cfg" "https://mgmt.omoti.de/Parts/Web/forwarding.cfg" "sed -i 's|link|${link}|' forwarding.cfg"
            process_certificates
            verify_nginx_deployment
        fi

    #add a proxy
        if [[ ${task} == 'proxy' ]]
        then
            dnsRecord
            deploy_nginx_site "proxy.cfg" "https://mgmt.omoti.de/Parts/Web/proxy.cfg" "sed -i 's|proxy_link|${proxy_link}|' proxy.cfg"
            process_certificates
            verify_nginx_deployment
        fi

    #git sync
        if [[ ${task} == 'git' ]]
        then
            for dir in /opt/*
            do
                if [[ -d "${dir}/.git" ]]
                then
                    echo -e "\033[36m$(basename "${dir}")\033[0m:"
                    (cd "${dir}" && git pull origin main)
                    echo
                fi
            done
            o_log -i 'All pages have been updated'
        fi

    #install web server
        if [[ ${task} == 'setup' ]]
        then
            #packages
                apt install -y nginx certbot python3-certbot-nginx apache2-utils git apt-transport-https lsb-release ca-certificates libcurl4

            #php
                wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
                sh -c 'echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'
                apt update
                apt upgrade -y
                apt install -y php php-fpm php-cli php-mbstring php-curl nullmailer

            #apache2
                sed -i 's/80/8000/' /etc/apache2/ports.conf
                systemctl stop apache2
                systemctl disable apache2

            #secure php
                for php_dir in /etc/php/*
                do
                    if [[ -f "${php_dir}/fpm/php.ini" ]]
                    then
                        sed -i 's/expose_php = On/expose_php = Off/' "${php_dir}/fpm/php.ini"
                        sed -i 's/;extension=openssl/extension=openssl/' "${php_dir}/fpm/php.ini"
                    fi
                done

            #secure nginx
                sed -i 's/# server_names_hash_bucket_size 64;/server_names_hash_bucket_size 64;/' /etc/nginx/nginx.conf
                sed -i 's/# server_tokens off;/server_tokens off;/' /etc/nginx/nginx.conf
                sed -i '/server_tokens off;/ a\        limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;' /etc/nginx/nginx.conf
                ensureVhostLogFormat
                systemctl restart nginx.service

            #default page
                cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default_save

                mkdir /opt/default/
                cd /opt/default/ || exit 1
                DownloadFile 'https://mgmt.omoti.de/Parts/Web/network.jpg'
                DownloadFile 'https://mgmt.omoti.de/Parts/Web/template.html'
                DownloadFile 'https://mgmt.omoti.de/Parts/Web/error.html'
                mv template.html index.html
                sed -i 's/code/Domain parked/g' index.html
                sed -i 's/description//' index.html

                sed -i 's|/var/www/html|/opt/default|' /etc/nginx/sites-available/default
                sed -i 's|server_name _;|server_name _;\n        error_page 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 421 422 423 424 425 426 428 429 431 451 500 501 502 503 504 505 506 507 508 510 511 /error.html;\n        location = /error.html {ssi on;internal;root /opt/default;}|' /etc/nginx/sites-available/default
                configureVhostLogging 'default' '/etc/nginx/sites-available/default'
                cd / || exit 1

            #firewall
                iptables -I INPUT 4 -p tcp --dport 80 -m comment --comment "http" -j ACCEPT
                ip6tables -I INPUT 4 -p tcp --dport 80 -m comment --comment "http" -j ACCEPT
                iptables -A INPUT -p tcp --dport 443 -m comment --comment "https" -j ACCEPT
                ip6tables -A INPUT -p tcp --dport 443 -m comment --comment "https" -j ACCEPT
                iptables-save > /etc/iptables/rules.v4
                ip6tables-save > /etc/iptables/rules.v6

            #git
                git config --global init.defaultBranch main
                git config --global pull.rebase true

            #crontab
                sed -i 's/# Example of job definition:/MAILTO=""\n\n# Example of job definition:/' /etc/crontab
                echo '*/30 * * * * root o_web -g' >> /etc/crontab

            #nullmailer
                echo '#netcup' > /etc/nullmailer/remotes
                echo 'mx2e4e.netcup.net smtp --user=USER --pass=PASSWORD --port=465 --tls' >> /etc/nullmailer/remotes
                echo "$(hostname -f)" > /etc/mailname
                echo "$(hostname -d)" > /etc/nullmailer/defaultdomain
                echo 'USER' > /etc/nullmailer/allmailfrom

                nano /etc/nullmailer/remotes
                nano /etc/nullmailer/allmailfrom

            # Nginx backup
                cd /srv/omoti/scripts/ || exit 1
                DownloadFile 'https://mgmt.omoti.de/Parts/Web/nginx_backup.sh'
                chmod 700 nginx_backup.sh
                cd / || exit 1

                echo '30 5 * * * root /srv/omoti/scripts/nginx_backup.sh' >> /etc/crontab

            systemctl restart nginx.service
        fi

    #parks a domain
        if [[ ${task} == 'park' ]]
        then
            dnsRecord
            deploy_nginx_site "parking.cfg" "https://mgmt.omoti.de/Parts/Web/parking.cfg"
            process_certificates
            verify_nginx_deployment
        fi
