#user  nobody;
worker_processes 1;

#error_log  logs/error.log  debug;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;
		root		 sgs; # TODO change to Simple Groupware root directory

		# WebDAV server
		#
		location ~ ^/sgdav {
			rewrite . /bin/webdav.php;
		}
		
		# CMS real URLs
		#
		location ~ ^/cms/ {
			rewrite ^/cms/ext/(.*)$ /bin/ext/cms/$1 last;
			rewrite ^/cms/thumbs/(.*)$ /bin/preview.php?filename=$1 last;
			rewrite ^/cms/(.*?)/file/(.*)$ /bin/cms.php?page=$1&file=$2 last;
			rewrite ^/cms/(.*)$ /bin/cms.php?page=$1 last; 
		}
		
        # Root
		#
		location = / {
			if ($request_method = "OPTIONS") {
				rewrite . /bin/webdav.php last;
			}
			try_files /bin/index.php /src/index.php /sgs_installer.php =404;
			
			include        fastcgi_params;
			fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
			fastcgi_pass   127.0.0.1:9000; # use spawn-fcgi (!!)
		}

		# Root PHP /*.php
		#
		location ~ ^/([^/]+\.php)$ {
			try_files /bin/$1 /src/$1 $uri =404;

            include        fastcgi_params;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_pass   127.0.0.1:9000; # use spawn-fcgi (!!)
		}
		
		# Sgs src/*.php bin/*.php
		#
		location ~ ^/(src|bin)/([^/]+\.php|ext/.+\.php)$ {
            include        fastcgi_params;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_pass   127.0.0.1:9000; # use spawn-fcgi (!!)
        }
		
		# Redirect static files
		#
		location ~ ^/(src/|bin/)?(ext/.*|docs/.*)$ {
			try_files /custom/$2 /ext/$2 /bin/$2 /src/$2 $uri =404;
		}

		# Drop all other stuff
		#
		location / {
			if (!-f $request_filename) {
				return 404;
			}
			return 403;
		}
    }
}