#!/bin/bash

# Create Required Folders for Liman
mkdir -p /liman/{server,certs,logs,database,sandbox,keys,extensions}

# User Creation
if getent passwd liman > /dev/null 2>&1; then
    echo "Liman User Found."
else
    useradd liman -m
    mkdir /home/liman
    chmod -R o= /liman /home/liman
    chown -R liman:liman /liman /home/liman
    echo "liman     ALL=(ALL:ALL) NOPASSWD:ALL" >> /etc/sudoers
    echo "Liman User Created"
fi

# Certificate Creation
if [ -f "/liman/certs/liman.crt" ]; then
    echo "SSL Certificate Found."
else
    openssl req \
        -new \
        -newkey rsa:4096 \
        -days 365 \
        -nodes \
        -x509 \
        -subj "/C=TR/ST=Ankara/L=Merkez/O=Havelsan/CN=liman" \
        -keyout /liman/certs/liman.key \
        -out /liman/certs/liman.crt
    echo "SSL Certificate Created"
fi

# Database Creation
if [ -f "/liman/database/liman.sqlite" ]; then
    echo "Database file found."
else
    touch /liman/database/liman.sqlite
    chmod 700 /liman/database/liman.sqlite
fi

# Update Php and Fpm to run as liman user.
sed -i "s/www-data/liman/g" /etc/php/7.3/fpm/pool.d/www.conf
sed -i "s/www-data/liman/g" /etc/nginx/nginx.conf

# Crontab Setting
if [ -f "/etc/cron.d/liman" ]; then
    echo "Crontab already created.";
else
    mkdir "/etc/cron.d" 2>/dev/null
    echo "* * * * * liman cd /liman/server && php artisan schedule:run >> /dev/null 2>&1" >> "/etc/cron.d/liman"
    systemctl restart cron
fi

mv /liman/server/nginx.conf /etc/nginx/sites-available/liman.conf
ln -s /etc/nginx/sites-available/liman.conf /etc/nginx/sites-enabled/liman.conf

# Fpm Optimizations
# if grep --quiet LIMAN_OPTIMIZATIONS /etc/php/7.3/fpm/php-fpm.conf; then
#     echo "Fpm settings already optimized."; 
# else
#     echo """
#     ;LIMAN_OPTIMIZATIONS
#     emergency_restart_threshold 10
#     emergency_restart_interval 1m
#     process_control_timeout 10s
#     """ >> /etc/php/7.3/fpm/php-fpm.conf
# fi

# Nginx Auto Redirection
if grep --quiet LIMAN_OPTIMIZATIONS /etc/nginx/sites-available/default; then
    echo "Nginx https redirection already set up."; 
else
    echo """
#LIMAN_OPTIMIZATIONS
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 301 https://\$host\$request_uri;
}
    """ > /etc/nginx/sites-available/default
fi

#Supervisor Configuration
if [ -f "/etc/supervisor/conf.d/liman-extension-worker.conf" ]; then
    echo "Supervisor already created.";
else
        echo """
#LIMAN_OPTIMIZATIONS
[program:liman-extension-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /liman/server/artisan queue:work --sleep=1 --tries=3 --queue=extension_queue
autostart=true
autorestart=true
user=liman
numprocs=8
redirect_stderr=true
stdout_logfile=/liman/logs/extension_queue.log
    """ > /etc/supervisor/conf.d/liman-extension-worker.conf
    supervisorctl reread
    supervisorctl update
fi
supervisorctl start liman-extension-worker

#Increase Php-Fpm Memory
sed -i "s/memory_limit = 128M/memory_limit = 1024M/g" /etc/php/7.3/fpm/php.ini

# Restart and enable services.
systemctl restart nginx
systemctl enable nginx
systemctl enable php7.3-fpm
systemctl restart php7.3-fpm

# Run Database Migration
php /liman/server/artisan migrate --force
php /liman/server/artisan cache:clear
php /liman/server/artisan view:clear
php /liman/server/artisan config:clear

# Clear Sandbox Cache
rm -rf /tmp/liman

# Set Permissions
chown -R liman:liman /liman/{server,database,certs,sandbox,logs}
chmod 700 -R /liman/{server,database,certs,logs}
chmod 755 -R /liman/sandbox
chown liman:liman /{liman,liman/extensions,liman/keys}
chmod 755 /{liman,liman/extensions,liman/keys}

# Create Systemd Service
if [ -f "/etc/systemd/system/liman.service" ]; then
    echo "Liman Connector Service Already Added.";
else
        echo """
[Unit]
Description=Liman Connector Service
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=root
ExecStart=/liman/server/storage/connector

[Install]
WantedBy=multi-user.target
    """ > /etc/systemd/system/liman.service
fi

# Create Systemd Service
if [ -f "/etc/systemd/system/liman-vnc.service" ]; then
    echo "Liman Connector Service Already Added.";
else
        echo """
[Unit]
Description=Liman VNC Service
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=liman
ExecStart=/usr/bin/websockify --web=/usr/share/novnc 6080 --cert=/liman/certs/liman.crt --key=/liman/certs/liman.key --token-plugin TokenFile --token-source /liman/keys/vnc/config
[Install]
WantedBy=multi-user.target
    """ > /etc/systemd/system/liman-vnc.service
fi

sed -i "s/upload_max_filesize.*/upload_max_filesize = 50M/g" /etc/php/7.3/fpm/php.ini

systemctl daemon-reload
systemctl enable liman
systemctl enable liman-vnc
systemctl restart liman
systemctl restart liman-vnc
systemctl reload php7.3-fpm.service
# Create Socket Service
if [ -f "/etc/systemd/system/liman-socket.service" ]; then
    echo "Liman Socket Service Already Added.";
else
        echo """
[Unit]
Description=Liman Socket Service
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=liman
ExecStart=/usr/bin/php /liman/server/artisan websockets:serve --host=127.0.0.1

[Install]
WantedBy=multi-user.target
    """ > /etc/systemd/system/liman-socket.service
fi
systemctl daemon-reload
systemctl enable liman-socket
systemctl restart liman-socket

# Copy Decoder
cp /liman/server/storage/decoder.so /usr/lib/php/20180731/liman-decoder.so
chmod 644 /usr/lib/php/20180731/liman-decoder.so

# Copy libphpcpp
cp /liman/server/storage/libphpcpp.so.2.2.0 /usr/lib/libphpcpp.so.2.2.0
ln -f -s /usr/lib/libphpcpp.so.2.2.0 /usr/lib/libphpcpp.so.2.2
chmod 644 /usr/lib/libphpcpp.so.2.2.0

# Prepare Folders for vnc
rm -rf /liman/keys/vnc
mkdir /liman/keys/vnc
chmod 700 /liman/keys/vnc
touch /liman/keys/vnc/config
chown liman:liman /liman/keys/vnc /liman/keys/vnc/config
chmod 700 /liman/keys/vnc/config


# Modify ini file to use decoder.
if grep --quiet liman-decoder.so /etc/php/7.3/cli/php.ini; then
    echo "Decoder already enabled"; 
else
    echo "extension=liman-decoder.so" >> /etc/php/7.3/cli/php.ini
fi

# Enable Liman
php /liman/server/artisan up

#Finalize Installation
printf "\nKurulum Başarıyla Tamamlandı\n\nYönetici Hesabı oluşturmak yada şifrenizi yenilemek için aşağıdaki komutu çalıştırabilisiniz\n\n\n"
printf "sudo runuser liman -c \"php /liman/server/artisan administrator\"\n\n\n"