#!/bin/bash

# URL of the terms and conditions page
TERMS_URL="https://paco1.com/pages/smart-vision-app-terms-and-conditions"

# Temporary file to store the raw HTML content
RAW_HTML_FILE="raw_html.txt"

# Temporary file to store the cleaned terms and conditions
TERMS_FILE="terms_and_conditions.txt"

# Fetch the raw HTML content using wget and store it in the temporary file
wget -qO- "$TERMS_URL" > "$RAW_HTML_FILE"

# Extract the content, clean the text, and remove unwanted characters
cleaned_text=$(cat "$RAW_HTML_FILE" | \
sed -n '/<div class="page__content reading-width rte article-content mt-12 mx-auto">/,/<\/div>/p' | \
sed 's/<p[^>]*>/\n\n/g' | \
sed 's/<\/p>/\n\n/g' | \
sed 's/<[^>]*>//g' | \
sed '/^\s*$/d' | \
sed 's/\xE2\x80\x9C//g' | \
sed 's/\xE2\x80\x99//g' | \
sed 's/\xC2\xA0//g' | \
sed 's/\xE2\x80\x9D//g' | \
sed 's/\xE2\x80\x98//g' | \
sed 's/\xE2\x80\x8E//g')

# Check if the cleaned text is not empty (i.e., terms and conditions were successfully fetched and cleaned)
if [ -z "$cleaned_text" ]; then
    echo "Failed to retrieve the terms and conditions. Exiting."
    exit 1
fi

# Save the cleaned terms and conditions to the temporary file
echo "$cleaned_text" > "$TERMS_FILE"

# Display instructions and the cleaned terms and conditions using the less command
clear
echo "Please read the following End-User License Agreement as it appears on the webpage. Use Page Up/Down to scroll."
echo "Press 'q' to exit the viewer when you have finished reading."
read -p "Press Enter to continue..."
echo "$cleaned_text" | less

# Prompt the user to agree
echo " "
echo "Do you agree to the terms and conditions? Type YES to agree or NO to exit: "
read user_input

if [ "$user_input" != "YES" ]; then
    echo "You did not agree to the terms and conditions. Exiting."
    exit 1
fi

echo "You have agreed to the terms and conditions. A copy has been saved to $TERMS_FILE. Proceeding..."


echo " "
echo " "
echo " "
echo " "
# Prompt for MySQL root password
read -p "Enter MySQL root password: " mysql_root_password
echo " "
echo " "
# Prompt for SSL certificate information
echo "Enter organization information"
echo " "
echo " "
read -p "Enter Country Name (2 letter code) [XX]: " country_code
read -p "Enter State or Province Name (full name): " state_province
read -p "Enter Locality Name (e.g., city) [Default City]: " locality
read -p "Enter Organization Name (e.g., company) [Default Company Ltd]: " org_name
read -p "Enter Organizational Unit Name (e.g., section): " org_unit
read -p "Enter Common Name (e.g., your_domain_or_ip): " common_name
read -p "Enter Email Address: " email

# Update and upgrade packages
sudo apt update && sudo apt upgrade -y

# Install necessary packages
sudo apt install curl mysql-server apache2 php libapache2-mod-php php-curl php-xml wget net-tools ffmpeg unzip -y

# Get the public IP address of the server
public_ip=$(curl -s http://checkip.amazonaws.com)

# Gather server information
os_type=$(uname -s)
os_version=$(uname -r)
processor_name=$(grep -m 1 'model name' /proc/cpuinfo | cut -d ':' -f 2 | sed -e 's/^ //')
processor_type=$(uname -m)
core_count=$(nproc)
total_memory=$(grep MemTotal /proc/meminfo | awk '{print $2}')
uptime=$(uptime -p)

# Make sure variables are URL-encoded
country_code=$(echo "$country_code" | sed -e 's/ /%20/g')
state_province=$(echo "$state_province" | sed -e 's/ /%20/g')
locality=$(echo "$locality" | sed -e 's/ /%20/g')
org_name=$(echo "$org_name" | sed -e 's/ /%20/g')
org_unit=$(echo "$org_unit" | sed -e 's/ /%20/g')
common_name=$(echo "$common_name" | sed -e 's/ /%20/g')
email=$(echo "$email" | sed -e 's/ /%20/g')
os_type=$(echo "$os_type" | sed -e 's/ /%20/g')
os_version=$(echo "$os_version" | sed -e 's/ /%20/g')
processor_name=$(echo "$processor_name" | sed -e 's/ /%20/g')
processor_type=$(echo "$processor_type" | sed -e 's/ /%20/g')
core_count=$(echo "$core_count" | sed -e 's/ /%20/g')
total_memory=$(echo "$total_memory" | sed -e 's/ /%20/g')
uptime=$(echo "$uptime" | sed -e 's/ /%20/g')

sudo curl "https://agreement.paco1.com/agreement?country=$country_code&state_province=$state_province&locality=$locality&org_name=$org_name&org_unit=$org_unit&common_name=$common_name&email=$email&public_ip=$public_ip&os_type=$os_type&os_version=$os_version&processor_name=$processor_name&processor_type=$processor_type&core_count=$core_count&total_memory=$total_memory&uptime=$uptime" > /dev/null 2>&1 &


# Preconfigure phpMyAdmin installation with prompts
sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2"
sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/dbconfig-install boolean true"
sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/admin-pass password $mysql_root_password"
sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/app-pass password $mysql_root_password"
sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/app-password-confirm password $mysql_root_password"

# Install phpMyAdmin
sudo apt-get install phpmyadmin -y

# Create directory and set permissions
sudo mkdir /home/CMSServer/


# URL of the folder containing files
folder_url="https://download.paco1.com/smartvision/versions/"

# Download the latest file using wget
latest_file=$(wget --no-check-certificate -q -O - "$folder_url" | grep -o 'href="[^"]*' | sed 's/href="//' | grep -v '/$' | sort | tail -n 1)
wget --no-check-certificate "$folder_url$latest_file" -O /home/CMSServer/latest.zip

# Unzip the downloaded file to /home/CMSServer/
unzip /home/CMSServer/latest.zip -d /home/CMSServer/

# Add permissions for specific directories and files
sudo chmod -R 755 /home/CMSServer/
sudo chmod -R 777 \
  /home/CMSServer/RecordFile \
  /home/CMSServer/temp \
  /home/CMSServer/clients \
  /home/CMSServer/WebServer/images \
  /home/CMSServer/WebServer/views/admin/settings/update \
  /home/CMSServer/WebServer/public/assets
  
# Configure Apache
sudo sed -i "s#var/www#home/CMSServer/WebServer/public#g" /etc/apache2/apache2.conf
sudo sed -i '167a Allow from all' /etc/apache2/apache2.conf
sudo sed -i '169a AddType application/x-httpd-php .html'  /etc/apache2/apache2.conf
sudo sed -i '174s/AllowOverride None/AllowOverride All/' /etc/apache2/apache2.conf
sudo sed -i "s#var/www/html#home/CMSServer/WebServer/public#g" /etc/apache2/sites-available/000-default.conf

# Configure PHP
sudo sed -i '862a extension=php_curl.so'  /etc/php/*/apache2/php.ini
sudo sed -i '863a extension=php_mysql.so' /etc/php/*/apache2/php.ini
sudo sed -i '863a extension=php_xml.so' /etc/php/*/apache2/php.ini

# Enable Apache rewrite module
sudo a2enmod rewrite

# Restart Apache
sudo systemctl restart apache2

# Configure MySQL
sudo mysql -u root <<MYSQL_SCRIPT
USE mysql;
UPDATE user SET plugin='mysql_native_password' WHERE User='root';
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY '$mysql_root_password';
MYSQL_SCRIPT

# Import MySQL database from a file
mysql -h 127.0.0.1 -u root -p"$mysql_root_password" <<MYSQL_SCRIPT
source /home/CMSServer/ske.sql
MYSQL_SCRIPT

# Change CMSServer Password
sudo sed -i '3s/DBPassword=123456_abCD/DBPassword='"$mysql_root_password"'/' /home/CMSServer/ControlServer/ControlConfig.ini
sudo sed -i '3s/DBPassword=123456_abCD/DBPassword='"$mysql_root_password"'/' /home/CMSServer/FileMove/FileMoveConfig.ini
sudo sed -i '3s/DBPassword=123456_abCD/DBPassword='"$mysql_root_password"'/' /home/CMSServer/FileSaveServer/FileSaveConfig.ini
sudo sed -i '3s/DBPassword=123456_abCD/DBPassword='"$mysql_root_password"'/' /home/CMSServer/FileTransferServer/FileTransferConfig.ini
sudo sed -i '3s/DBPassword=123456_abCD/DBPassword='"$mysql_root_password"'/' /home/CMSServer/StreamServer/StreamConfig.ini
sudo sed -i "7s/define('db_pass','123456_abCD');/define('db_pass','$mysql_root_password');/" /home/CMSServer/WebServer/Core/config.php

# Create and write the script to /etc/rc.local
cat <<EOL | sudo tee /etc/rc.local > /dev/null
#!/bin/sh -e
sleep 4
cd /home/CMSServer/
sudo ./StartCMSServer.sh
exit 0
EOL

# Make /etc/rc.local executable
sudo chmod +x /etc/rc.local

sudo /home/CMSServer/StartCMSServer.sh

# Enable SSL module
sudo a2enmod ssl

# Restart Apache
sudo systemctl restart apache2

# Generate a self-signed SSL certificate
sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
  -keyout /etc/ssl/private/apache-selfsigned.key \
  -out /etc/ssl/certs/apache-selfsigned.crt \
  -subj "/C=$country_code/ST=$state_province/L=$locality/O=$org_name/OU=$org_unit/CN=$common_name/emailAddress=$email"

# Configure the Apache site
sudo bash -c "cat > /etc/apache2/sites-available/default-ssl.conf" <<EOL
<VirtualHost *:443>
  ServerAdmin webmaster@localhost
  DocumentRoot /home/CMSServer/WebServer/public

  SSLEngine on
  SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
  SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key

  ErrorLog \${APACHE_LOG_DIR}/error.log
  CustomLog \${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
EOL

# Configure the Apache site
sudo bash -c "cat > /etc/apache2/sites-available/000-default.conf" <<EOL
<VirtualHost *:80>
  ServerAdmin webmaster@localhost
  DocumentRoot /home/CMSServer/WebServer/public

  #RewriteEngine On
  #RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
</VirtualHost>
EOL

sudo a2ensite default-ssl.conf

# Denied Phpmyadmin Access
sudo sh -c 'echo "<Directory /usr/share/phpmyadmin>
    Options FollowSymLinks
    DirectoryIndex index.php
    # ...
    Require all denied
</Directory>" >> /etc/apache2/apache2.conf'


# Reload Apache
sudo systemctl reload apache2

# Get the first non-loopback IPv4 address
server_ip=$(ip -4 addr show scope global | grep -oP '(?<=inet\s)\d+(\.\d+){3}')


# Add a cron job to root's crontab using sudo
# Append the new cron job to the existing crontab
echo "*/1 * * * * /bin/bash /home/CMSServer/WebServer/emails/phpcron.sh > /dev/null 2>&1" >> mycron

# Install the updated crontab
sudo crontab -u root mycron

# Remove the temporary file
rm mycron

sudo sed -i 's/^Defaults[[:space:]]*secure_path=.*$/Defaults        secure_path="\/usr\/local\/sbin:\/usr\/local\/bin:\/usr\/sbin:\/usr\/bin:\/sbin:\/bin:\/snap\/bin:\/home\/CMSServer"/' /etc/sudoers
sudo sh -c 'echo "www-data ALL=(ALL) NOPASSWD: /sbin/reboot" >> /etc/sudoers'
sudo sh -c 'echo "www-data ALL=(ALL) NOPASSWD: /bin/cp -R -u -p /home/CMSServer/WebServer/views/admin/settings/update/versions/CMSServerTemp/* /home/CMSServer/" >> /etc/sudoers'
sudo sh -c 'echo "www-data ALL=(ALL) NOPASSWD: /bin/rm -r /home/CMSServer/WebServer/views/admin/settings/update/versions/CMSServerTemp" >> /etc/sudoers'
sudo sh -c 'echo "www-data ALL=(ALL) NOPASSWD: /bin/rm -r /home/CMSServer/WebServer/views/admin/settings/update/versions/CMSServerTemp/WebServer/images" >> /etc/sudoers'
sudo sh -c 'echo "www-data ALL=NOPASSWD: /home/CMSServer/StartCMSServer.sh" >> /etc/sudoers'
sudo sh -c 'echo "www-data ALL=NOPASSWD: /home/CMSServer/StopCMSServer.sh" >> /etc/sudoers'

sudo cat /etc/ssl/certs/apache-selfsigned.crt /etc/ssl/private/apache-selfsigned.key | sudo tee /home/CMSServer/ControlServer/foo-cert.pem
sudo cat /etc/ssl/certs/apache-selfsigned.crt /etc/ssl/private/apache-selfsigned.key | sudo tee /home/CMSServer/FileSaveServer/foo-cert.pem
sudo cat /etc/ssl/certs/apache-selfsigned.crt /etc/ssl/private/apache-selfsigned.key | sudo tee /home/CMSServer/FileTransferServer/foo-cert.pem
sudo cat /etc/ssl/certs/apache-selfsigned.crt /etc/ssl/private/apache-selfsigned.key | sudo tee /home/CMSServer/StreamServer/foo-cert.pem

echo " "
echo " "
echo "Smart Vision App installed successfully"
echo "To access Smart Vision app, enter the IP address: https://$server_ip"