#!/bin/bash
set -e

sudo apt update
sudo apt install -y apache2 apache2-utils

SHARE=/var/www/webdav
sudo mkdir -p "$SHARE"
sudo chown -R www-data:www-data "$SHARE"
sudo chmod -R 755 "$SHARE"

sudo a2enmod dav dav_fs
sudo systemctl reload apache2

LOCKDIR=/usr/local/apache/var/DavLock
sudo mkdir -p "$LOCKDIR"
sudo chown www-data:www-data "$LOCKDIR"

sudo tee /etc/apache2/sites-available/webdav.conf > /dev/null <<EOF
<VirtualHost *:80>
    ServerAdmin admin@$(hostname -f)
    DavLockDB $LOCKDIR/DavLock
    Alias /webdav $SHARE
    DocumentRoot /var/www/webdav
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory $SHARE>
        DAV On
        AllowOverride None
        Order allow,deny
        allow from all
        Options Indexes FollowSymLinks MultiViews
    </Directory>
</VirtualHost>
EOF

sudo tee /etc/apache2/sites-available/000-default.conf > /dev/null <<EOF
DavLockDB $LOCKDIR/DavLock
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    Alias /webdav $SHARE
    DocumentRoot /var/www/html
    <Directory /var/www/webdav>
    
        DAV On
    
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
EOF

sudo a2ensite webdav.conf
sudo systemctl reload apache2

echo ""
echo "✅ WebDAV setup complete!"
echo "Access via: http://$(hostname -I | awk '{print $1}')/webdav/"
