#!/bin/bash

#Take Arguments
NEXTCLOUD_DOWNLOAD_LINK="https://download.nextcloud.com/server/releases/latest.zip"
NEXTCLOUD_APP_NAME=""

#Upgrade systservicessem
apt update
apt upgrade -y

#disable interactive mode
export DEBIAN_FRONTEND=noninteractive

#Install prerequisites
apt install -y wget vim zip

#Install apache2
apt install -y apache2 php8.1 libapache2-mod-php8.1
#Install required php modules
apt install -y php8.1-common php8.1-curl php8.1-dom php8.1-gd php8.1-mbstring php8.1-xml php8.1-zip php8.1-mysql
#Install optionnal php modules
apt install -y php8.1-bz2 php8.1-intl php8.1-ldap php8.1-smbclient php8.1-imap php8.1-bcmath php8.1-gmp php8.1-apcu 

#Go into apache directory
cd /etc/apache2/sites-available

#Disable all sites
a2dissite *

#Create site Configuration file
touch /etc/apache2/sites-available/nextcloud-http.conf
cat << EOF >> /etc/apache2/sites-available/nextcloud-http.conf
<VirtualHost *:80>
  DocumentRoot /var/www/nextcloud/
  ServerName  $NEXTCLOUD_APP_NAME

  <Directory /var/www/nextcloud/>
    Require all granted
    AllowOverride All
    Options FollowSymLinks MultiViews

    <IfModule mod_dav.c>
      Dav off
    </IfModule>
  </Directory>
</VirtualHost>
EOF

#Enable nextcloud site
a2ensite nextcloud-http

#Enable necessary apache module
a2enmod rewrite env dir mime

#Create website directory
mkdir /var/www/nextcloud

#Go into apache directory
cd /var/www/

#Download nextcloud installer
wget $NEXTCLOUD_DOWNLOAD_LINK

#Unzip
unzip *.zip

#Remove zip file
rm *.zip

#set permissions
chown -R www-data:www-data /var/www/nextcloud/

#restart apache2 service
service apache2 restart