#!/bin/ksh

#########################################################
# FONCTIONS

testjoyentRepo () {

    if command -v pkgin >/dev/null 2>&1; then
        echo "The Joyent repository is already installed"
    else
        echo "The Joyent repository is not yet installed"
        echo ""
        joyentRepo
    fi

}

joyentRepo () {

    cd /tmp
    BOOTSTRAP_TAR="bootstrap-trunk-x86_64-20240116.tar.gz"
    BOOTSTRAP_SHA="4d92a333587d9dcc669ff64264451ca65da701b7"
    curl -O https://pkgsrc.smartos.org/packages/SmartOS/bootstrap/${BOOTSTRAP_TAR}
    tar -zxpf ${BOOTSTRAP_TAR} -C /
    sed -i 's/PATH=\(.*\)/PATH=\1:\/opt\/local\/sbin:\/opt\/local\/bin/' /etc/default/login

    cd /tmp
    UPGRADE_TAR="bootstrap-trunk-x86_64-20240116-upgrade.tar.gz"
    UPGRADE_SHA="3099211460e84c34b9f558c8f7354a871187be41"
    curl -O https://pkgsrc.smartos.org/packages/SmartOS/bootstrap-upgrade/${UPGRADE_TAR}
    tar -zxpf ${UPGRADE_TAR} -C /
    echo 'PATH=/opt/local/sbin:/opt/local/bin:$PATH' >> /etc/profile
    echo 'MANPATH=/opt/local/man:$MANPATH' >> /etc/profile 

    alias pkg_add=/opt/local/sbin/pkg_add
    alias pkgin=/opt/local/bin/pkgin
    pkg_add -U pkg_install pkgin libarchive
    pkgin clean
    pkgin -y upgrade

}

sfeRepo () {

    pfexec pkg set-publisher -G '*' -g https://sfe.opencsw.org/localhostomnios localhostomnios
    pkg refresh

}

frenchHour () {

    pkg install ntpsec && /usr/bin/ntpdate 0.fr.pool.ntp.org && date && svcadm enable svc:/network/ntp:default
}

locatecmd () {

    testjoyentRepo
    pkgin update
    pkgin -y in findutils
    updatedb
}

shortenboot () {

    echo 'autoboot_delay="0"' >> /boot/loader.conf.local
    echo 'beastie_disable="YES"' >> /boot/loader.conf.local

}

miniIRCd () {

    pkg install git
    cd /tmp
    git clone https://github.com/jrosdahl/miniircd.git
    cd miniircd
    cp miniircd /usr/bin/

    mkdir -p /var/jail/miniircd
    cd /var/jail/miniircd
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout miniircd.key -out miniircd.crt 

    nohup /usr/bin/miniircd  --listen=0.0.0.0 --ssl-cert-file=/var/jail/miniircd/miniircd.crt --ssl-key-file=/var/jail/miniircd/miniircd.key --verbose --chroot=/var/jail/miniircd --setuid=nobody &
}

XorgTwm () {

    testjoyentRepo

    pkg install xsvc
    pkgin -y in modular-xorg
    pkgin -y in twm

    echo ""
    echo "----------------------------------------"
    echo "Do you want to restart now? [y/n]"
    read ans

    case $ans in  
        y|Y)
            reboot
        ;;
        n|N)
            MainMenu
        ;;
    esac

}

IPFilter () {
    
    clear
    echo "----------------------------------------"
    echo "Here are the available network cards"
    echo ""

    dladm | cut -d' ' -f1 | sed '/LINK/d'

    echo ""
    echo "----------------------------------------"
    echo "Please enter the name of the WAN network interface"
    read nic

    {

        echo "### IPFILTER CONFIGURATION ###"

        echo "# Default block for all traffic (inbound and outbound)"
        echo "block in log all"
        echo "block out log all"
        echo ""
        echo "# Blocking packets with suspicious IP options"
        echo "block in log quick from any to any with ipopts"
        echo ""
        echo "# Blocking malformed TCP packets"
        echo "block in log quick proto tcp from any to any with short"
        echo ""
        echo "# Blocking packets that are too short"
        echo "block in log quick all with short"
        echo ""
        echo "# Specific handling of local traffic (127.0.0.0/8)"
        echo "block in log quick from 127.0.0.0/8 to any"
        echo "block in log quick from any to 127.0.0.0/8"
        echo ""
        echo "# Beginning of ruleset for outgoing traffic on interface $nic"
        echo "block out on $nic all head 150"
        echo "block out from 127.0.0.0/8 to any group 150"
        echo "block out from any to 127.0.0.0/8 group 150"
        echo "#block out from any to inet6 ::/0 /32 group 150"
        echo ""
        echo "# Beginning of ruleset for incoming traffic on interface $nic"
        echo "block in on $nic all head 100"
        echo "block in from 127.0.0.0/8 to any group 100"
        echo "#block in from inet6 ::/0 /32 to any group 100"
        echo ""
        echo "# Allowing SSH connections"
        echo "pass in quick on $nic proto tcp from any to any port = 22"
        echo ""
        echo "# Allowing HTTP and HTTPS connections"
        echo "pass in quick on $nic proto tcp from any to any port = 80"
        echo "pass in quick on $nic proto tcp from any to any port = 443"
        echo ""
        echo "# Allowing traffic on the loopback interface (lo0)"
        echo "pass in quick on lo0 all"
        echo "pass out quick on lo0 all"
        echo ""
        echo "# Allow outgoing DHCP requests (from client to server)"
        echo "pass out quick on $nic proto udp from any port = 68 to any port = 67"
        echo ""
        echo "# Allow incoming DHCP responses (from server to client)"
        echo "pass in quick on $nic proto udp from any port = 67 to any port = 68"
        echo ""
        echo "# Handling of outgoing traffic allowed on interface $nic"
        echo "pass out on $nic all"
        echo ""
        echo "# Handling of incoming traffic allowed on interface $nic"
        echo "pass in on $nic all"

    } > /etc/ipf/ipf.conf

    svcadm enable ipfilter && sleep 3

    ipf -f /etc/ipf/ipf.conf && sleep 3

    clear
    echo "----------------------------------------"
    echo "Active rules"
    echo ""

    ipfstat -io

    echo ""

}

WordpressApache () {

    clear
    echo "----------------------------------------"
    echo "         WORDPRESS INSTALLATION"
    echo "----------------------------------------"
    echo ""
    echo "Here are the steps:"
    echo "- Installing Apache"
    echo "- Installing MariaDB"
    echo "- Prompt for a name for the SQL database creation for Wordpress"
    echo "- Prompt for a name for the privileged user on the SQL database"
    echo "- Prompt for the password for the privileged user on the SQL database"
    echo "- Installing PHP"
    echo "- Configuring PHP"
    echo "- Downloading Wordpress"
    echo "- Configuring Wordpress"
    echo "- Prompt for the ServerName for wordpress VirtualHost"
    echo "- Configuring Apache"
    echo "- Prompt for the desired HTTP socket"
    echo "- Prompt for the desired HTTPS socket"
    echo "- A final summary will present what has been done"
    echo ""


    echo "----------------------------------------"
    echo "Do you want to continue? [y/n]"
    read ans
    case $ans in
        n|N)
            MainMenu
        ;;
    esac
    echo ""

    echo "----------------------------------------"
    echo "Installing Apache..."
    echo ""

    pkg install pkg:/ooce/server/apache-24
    sleep 5
    mkdir /etc/opt/ooce/apache-2.4/SSL
    sleep 1
    echo ""


    echo "----------------------------------------"
    echo "Installing MariaDB..."
    echo "" 
    
    pkg install pkg:/ooce/database/mariadb-1011
    sleep 5
    svcadm enable svc:/ooce/database/mariadb1011:default
    sleep 10
    echo ""
    
    check=$(svcs svc:/ooce/database/mariadb1011:default | grep "online" | wc -l | tr -d '' | sort | uniq)
    if [ "$check" -eq 0 ]; then

        echo "----------------------------------------"
        echo "Second attempt to start MariaDB..."
        echo ""
        svcadm enable svc:/ooce/database/mariadb1011:default
        sleep 10
        echo ""

    fi

    echo "----------------------------------------"
    echo "Please enter a name for the SQL database for WordPress"
    echo "(example : wordpressdb)"
    read sqlbase

    mysqladmin -uroot create "$sqlbase"
    echo ""

    echo "----------------------------------------"
    echo "Please enter a name for the privileged user on the $sqlbase database"
    echo "(example : adminwp)"
    read sqluser
    echo ""

    echo "----------------------------------------"
    echo "Please enter a password for the privileged user $sqluser"
    read sqluserpass

    mysql -uroot -e"CREATE USER '$sqluser'@'localhost' IDENTIFIED BY '$sqluserpass'"
    sleep 1
    mysql -uroot -e"GRANT ALL ON \`${sqlbase}\`.* TO '${sqluser}'@'localhost'"
    echo ""
    sleep 1
    
    echo "----------------------------------------"
    echo "Installing PHP..."
    echo ""

    pkg install pkg:/ooce/application/php-83
    echo ""

    echo "----------------------------------------"
    echo "Configuring PHP..."
    echo ""

    sed -i 's/;extension=curl/extension=curl/' /etc/opt/ooce/php-8.3/php.ini
    sleep 1
    sed -i 's/;extension=gd/extension=gd/' /etc/opt/ooce/php-8.3/php.ini
    sleep 1
    sed -i 's/;extension=mbstring/extension=mbstring/' /etc/opt/ooce/php-8.3/php.ini
    sleep 1
    sed -i 's/;extension=zip/extension=zip/' /etc/opt/ooce/php-8.3/php.ini
    sleep 1
    sed -i 's/;extension=exif/extension=exif/' /etc/opt/ooce/php-8.3/php.ini
    sleep 1
    sed -i 's/;extension=openssl/extension=openssl/' /etc/opt/ooce/php-8.3/php.ini
    sleep 1
    sed -i 's/;extension=fileinfo/extension=fileinfo/' /etc/opt/ooce/php-8.3/php.ini
    sleep 1
    sed -i 's/;zend_extension=opcache/zend_extension=opcache/' /etc/opt/ooce/php-8.3/php.ini
    sleep 1
    sed -i 's/;extension=mysqli/extension=mysqli/' /etc/opt/ooce/php-8.3/php.ini

    # Starting PHP
    svcadm disable svc:/application/php83:default
    sleep 5
    svcadm enable svc:/application/php83:default
    sleep 10

    # Adding the user php to the group webservd
    usermod -G webservd php
    sleep 1
    echo ""

    echo "----------------------------------------"
    echo "Installing WordPress..."
    echo ""

    mkdir /var/www
    wget http://wordpress.org/latest.tar.gz -P /var/www/
    sleep 1
    tar -xvzf /var/www/latest.tar.gz -C /var/www/
    sleep 1
    rm /var/www/latest.tar.gz
    sleep 1
    echo ""

    echo "----------------------------------------"
    echo "Configuring WordPress..."
    echo ""

    # Configuring the wp-config.php file to indicate the information about the SQL database
    cp /var/www/wordpress/wp-config-sample.php /var/www/wordpress/wp-config.php
    sleep 1
    sed -i "s/database_name_here/${sqlbase}/" /var/www/wordpress/wp-config.php
    sleep 1
    sed -i "s/username_here/${sqluser}/" /var/www/wordpress/wp-config.php
    sleep 1
    sed -i "s/password_here/${sqluserpass}/" /var/www/wordpress/wp-config.php
    sleep 1
    sed -i 's/localhost/127.0.0.1/' /var/www/wordpress/wp-config.php

    # Configuring permissions on the DocumentRoot
    find /var/www/wordpress -type d -exec chmod 755 {} \;
    sleep 1
    find /var/www/wordpress -type f -exec chmod 644 {} \;
    sleep 1
    chmod 640 /var/www/wordpress/wp-config.php
    sleep 1
    chown -R webservd:webservd /var/www/wordpress
    sleep 1
    echo ""

    echo "----------------------------------------"
    echo "ServerName choice..."
    echo ""
    echo "Please enter a ServerName for your wordpress site"
    echo "(example : www.wordpress.lan)"
    read srvname
    echo ""

    mv /var/www/wordpress /var/www/"${srvname}" 


    echo "----------------------------------------"
    echo "Configuring Apache..."
    echo ""

    # Creating the log file
    mkdir -p /opt/ooce/apache-2.4/logs/
    sleep 1
    chown webservd:webservd /opt/ooce/apache-2.4/logs/
    sleep 1
    chmod 755 /opt/ooce/apache-2.4/logs/
    sleep 1

    # Creating the virtual host and self-signed SSL certificate
    cd /etc/opt/ooce/apache-2.4/SSL

    echo "----------------------------------------"
    echo "Please first enter the necessary information for creating your own certificate authority"
    echo "(you can leave everything blank for testing if you want)"
    echo ""

    openssl genrsa 4096 > ca.key
    sleep 1
    openssl req -new -x509 -days 365 -nodes -key ca.key > ca.crt
    sleep 1
    openssl genrsa 4096 > cleprivapache.key
    sleep 1
    echo ""

    echo "----------------------------------------"
    echo "Please now enter the necessary information for creating your SSL certificate signing request"
    echo "This request will be self-signed by the previously created certificate authority"
    echo "(you can leave everything blank for testing if you want)"
    echo ""

    openssl req -new -key cleprivapache.key > demandesignature.csr
    sleep 1
    openssl x509 -req -in demandesignature.csr -out certifapache.crt -CA ca.crt -CAkey ca.key -CAcreateserial -days 365
    sleep 1

    chown webservd:webservd cleprivapache.key
    chmod 640 cleprivapache.key
    chown webservd:webservd certifapache.crt
    chmod 644 certifapache.crt

    echo ""
    echo "----------------------------------------"
    echo "Here is the result of the 'ipadm' command"
    echo ""
    ipadm
    echo ""
    echo "----------------------------------------"
    echo "Please enter the desired HTTP socket"
    echo "(it's the combination of your server's IP with the desired HTTP port)"
    echo "(example: 192.168.1.200:80 or 192.168.1.200:8080)"
    read sockettoredir
    echo ""
    echo "----------------------------------------"
    echo "Please enter the desired HTTPS socket"
    echo "(it's the combination of your server's IP with the desired HTTPS port)"
    echo "(example: 192.168.1.200:443 or 192.168.1.200:4443)"
    read socket
    echo ""


    # Get the desired HTTPS port:
    choixhttps=$(echo $socket | cut -d: -f2)

    {
        echo "#### VHOST WORDPRESS ####"
        echo ""
        echo "Listen $choixhttps"
        echo ""
        echo 'SSLCipherSuite HIGH:MEDIUM:!MD5:!RC4:!3DES'
        echo 'SSLProxyCipherSuite HIGH:MEDIUM:!MD5:!RC4:!3DES'
        echo "SSLHonorCipherOrder on"
        echo "SSLProtocol all -SSLv3"
        echo "SSLProxyProtocol all -SSLv3"
        echo "SSLPassPhraseDialog  builtin"
        echo 'SSLSessionCache        "shmcb:/var/opt/ooce/apache-2.4/run/ssl_scache(512000)"'
        echo "SSLSessionCacheTimeout  300"
        echo ""
        echo "# REDIRECTION HTTP -> HTTPS"
        echo "<VirtualHost $sockettoredir>"
        echo "  ServerName $srvname"
        echo "  Redirect permanent / https://$srvname:$choixhttps/"
        echo "</VirtualHost>"
        echo ""
        echo "<VirtualHost $socket>"
        echo ' '
        echo "  ServerAdmin admin@$srvname"
        echo "  DocumentRoot \"/var/www/$srvname\""
        echo "  ServerName $srvname:$choixhttps" 
        echo "  ErrorLog \"/opt/ooce/apache-2.4/logs/$srvname-error_log\""
        echo "  CustomLog \"/opt/ooce/apache-2.4/logs/$srvname-access_log\" common"
        echo ' '
        echo "  SSLEngine on"
        echo ''
        echo '  SSLCertificateFile "/etc/opt/ooce/apache-2.4/SSL/certifapache.crt'
        echo '  SSLCertificateKeyFile "/etc/opt/ooce/apache-2.4/SSL/cleprivapache.key'
        echo " "
        echo "  <Directory \"/var/www/$srvname\">"
        echo '      AllowOverride All'
        echo '      Require all granted'
        echo '      DirectoryIndex index.php index.html index.htm'
        echo '  </Directory>'
        echo ' '
        echo '  <FilesMatch "\.(cgi|shtml|phtml|php)$">'
        echo '      SetHandler "proxy:unix:/var/opt/ooce/php/run/www-8.3.sock|fcgi://localhost/"'
        echo '      SSLOptions +StdEnvVars'
        echo '  </FilesMatch>'
        echo ''
        echo '  <Directory "/var/opt/ooce/apache-2.4/cgi-bin">'
        echo '      SSLOptions +StdEnvVars'
        echo '      </Directory>'
        echo ""
        echo 'BrowserMatch "MSIE [2-5]" \'
        echo '      nokeepalive ssl-unclean-shutdown \'
        echo '      downgrade-1.0 force-response-1.0'
        echo ' '
        echo 'CustomLog "/var/log/opt/ooce/apache-2.4/ssl_request_log" \'
        echo '      "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"'
        echo ''
        echo '</VirtualHost>'

    } > /etc/opt/ooce/apache-2.4/extra/"${srvname}".conf

    # Add the virtual host to the list of virtual hosts to execute:
    {
        echo ' '
        echo '#-------------------------#'
        echo '# Wordpress VirtualHost'
        echo "Include /etc/opt/ooce/apache-2.4/extra/${srvname}.conf"

    } >> /etc/opt/ooce/apache-2.4/httpd.conf

    # Configure Apache for PHP
    sed -i 's/#LoadModule proxy_module libexec\/mod_proxy.so/LoadModule proxy_module libexec\/mod_proxy.so/' /etc/opt/ooce/apache-2.4/httpd.conf
    sleep 1
    sed -i 's/#LoadModule proxy_fcgi_module libexec\/mod_proxy_fcgi.so/LoadModule proxy_fcgi_module libexec\/mod_proxy_fcgi.so/' /etc/opt/ooce/apache-2.4/httpd.conf
    sleep 1

    # Configure Apache for SSL
    sed -i 's/#LoadModule socache_shmcb_module libexec\/mod_socache_shmcb.so/LoadModule socache_shmcb_module libexec\/mod_socache_shmcb.so/' /etc/opt/ooce/apache-2.4/httpd.conf
    sleep 1
    sed -i 's/#LoadModule ssl_module libexec\/mod_ssl.so/LoadModule ssl_module libexec\/mod_ssl.so/' /etc/opt/ooce/apache-2.4/httpd.conf
    sleep 1
    sed -i 's/#LoadModule setenvif_module libexec\/mod_setenvif.so/LoadModule setenvif_module libexec\/mod_setenvif.so/' /etc/opt/ooce/apache-2.4/httpd.conf
    sleep 1
    sed -i 's/#LoadModule log_config_module libexec\/mod_log_config.so/LoadModule log_config_module libexec\/mod_log_config.so/' /etc/opt/ooce/apache-2.4/httpd.conf
    sleep 1

    echo "----------------------------------------"
    echo "Starting Apache..."
    echo ""


    svcadm disable svc:/network/http:apache24
    sleep 5
    svcadm enable svc:/network/http:apache24
    sleep 5
    echo ""

    ##################################
    # Pre-summary checks:

    # MariaDB
    checksql=$(svcs svc:/ooce/database/mariadb1011:default | grep "online" | sort | uniq | wc -l | tr -d '')
    case $checksql in
        0)
            checksql="offline"
        ;;
        1)
            checksql="online"
        ;;
    esac

    # Apache
    checkhttpd=$(svcs svc:/network/http:apache24 | grep "online" | sort | uniq | wc -l | tr -d '')
    case $checkhttpd in
        0)
            checkhttpd="offline"
        ;;
        1)
            checkhttpd="online"
        ;;
    esac

    # PHP
    checkphp=$(svcs svc:/application/php83:default | grep "online" | sort | uniq | wc -l | tr -d '')
    case $checkphp in
        0)
            checkphp="offline"
        ;;
        1)
            checkphp="online"
        ;;
    esac

    ##################################
    # Final Summary

    echo "----------------------------------------"
    echo "SUMMARY..."
    echo ""

    echo "DocumentRoot          : /var/www/$srvname"
    echo "VirtualHost           : /etc/opt/ooce/apache-2.4/extra/$srvname.conf"
    echo ""
    echo "SQL base              : ${sqlbase}"
    echo "SQL base user         : ${sqluser}"
    echo "SQL base user password: ${sqluserpass}"
    echo ""
    echo "MariaDB Status        : $checksql"
    echo "Apache Status         : $checkhttpd"
    echo "PHP Status            : $checkphp"
    echo ""
    echo "HTTP Socket           : $sockettoredir"
    echo "HTTPS Socket          : $socket"
    echo "HTTP -> HTTPS Redir.  : YES"
    echo ""
    echo "After adding the mapping between the server's IP and $srvname in the hosts file on your client computer, you should be able to access your site via"
    echo "http://$srvname or https://$srvname"

    echo ""
    echo "Press ENTER to go back to MainMenu"
    read ENTER

    MainMenu

}


#########################################################
# MENU PRINCIPAL

MainMenu () {
    clear
    echo "----------------------------------------"
    echo "                OMNIOS                  "
    echo "----------------------------------------"
    echo ""
    echo "[1] - Install Joyent repository (pkgsrc)"
    echo "[2] - Install SFE repository"
    echo "[3] - Set French time"
    echo "[4] - Install locate command"
    echo "[5] - Remove boot delay"
    echo "[6] - Configure miniIRCd"
    echo "[7] - Install Xorg and TWM"
    echo "[8] - Configure IPF firewall"
    echo "[9] - Install Wordpress on Apache"
    echo ""
    echo "----------------------------------------"
    echo "[q] - Quit"
    echo "----------------------------------------"
    echo ""
    echo "Make your choice"
    read choice

    case $choice in
        1)
            testjoyentRepo
        ;;
        2)
            sfeRepo
        ;;
        3)
            frenchHour
        ;;
        4)
            locatecmd
        ;;
        5)
            shortenboot
        ;;
        6)
            miniIRCd
        ;;
        7)
            XorgTwm
        ;;
        8)
            IPFilter
        ;;
        9)
            WordpressApache
        ;;
        q)
            exit 0
        ;;
    esac
}

MainMenu