#!/bin/sh

WEBROOT=/data/www
WEBDAV_PORT=${WEBDAV_PORT:-8080}
PHP=${PHP:-none}
USERNAME=${USERNAME:-theuser}
PUID=${PUID:-1000}
GROUPNAME=${GROUPNAME:-thegroup}
PGID=${PGID:-1000}
RANDOMPWD=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 13)
addgroup -g "${PGID}" "${GROUPNAME}"
addgroup nginx "${GROUPNAME}"
adduser -DH -h "${WEBROOT}" -G "${GROUPNAME}" -u "${PUID}" "${USERNAME}"
printf '%s\n%s' "${RANDOMPWD}" "${RANDOMPWD}" | passwd "${USERNAME}"
echo "password for the user \"${USERNAME}\" is: ${RANDOMPWD}"

chown "${PUID}:${GROUPNAME}" "${WEBROOT}" -R
find "${WEBROOT}" -type d -exec chmod 0755 {} \;
find "${WEBROOT}" -type f -exec chmod 0644 {} \;

FPM_MAX_CHILDREN=${FPM_MAX_CHILDREN:-5}
FPM_START_SERVERS=${FPM_START_SERVERS:-1}
FPM_MIN_SPARE_SERVERS=${FPM_MIN_SPARE_SERVERS:-1}
FPM_MAX_SPARE_SERVERS=${FPM_MAX_SPARE_SERVERS:-3}

# set php config
case "${PHP}" in
  "php7")
    cat >"/etc/${PHP}/php-fpm.d/www.conf" <<EOF
[www]
user = ${USERNAME}
group = ${GROUPNAME}
listen = 127.0.0.1:9000
pm = dynamic
pm.max_children = ${FPM_MAX_CHILDREN}
pm.start_servers = ${FPM_START_SERVERS}
pm.min_spare_servers = ${FPM_MIN_SPARE_SERVERS}
pm.max_spare_servers = ${FPM_MAX_SPARE_SERVERS}
EOF
    ;;
    *) ;;
esac

# start php
case "${PHP}" in
    "php7") 
      cp /app/nginx/php7.conf /etc/nginx/custom.d/
      cp /app/nginx/default_php.conf /etc/nginx/http.d/default.conf
      /usr/sbin/php-fpm7 -D
      ;;
    *)
      cp /app/nginx/default_nophp.conf /etc/nginx/http.d/default.conf
      ;;
esac

# start ssh
for keytype in ecdsa rsa ed25519 ; do
  if [ ! -r "/ssh/ssh_host_${keytype}_key" ] ; then
    /usr/bin/ssh-keygen -t "${keytype}" -f "/ssh/ssh_host_${keytype}_key" -N ""
  fi
  chmod 0600 "/ssh/ssh_host_${keytype}_key"
  chmod 0644 "/ssh/ssh_host_${keytype}_key.pub"
done

# set authorized_keys permissions
if [ -f /ssh/authorized_keys ] ; then
  chmod 0600 /ssh/authorized_keys
  chown "${USERNAME}:${GROUPNAME}" /ssh/authorized_keys
fi

chmod 0700 "${WEBROOT}/.ssh"
/usr/sbin/sshd -e

cat > /etc/nginx/conf.d/user.conf <<EOF
user ${USERNAME} ${GROUPNAME};
EOF

# fix permissions for upload
chown "${USERNAME}" /var/lib/nginx

cat > /etc/nginx/http.d/webdav.conf <<EOF
server {
    listen ${WEBDAV_PORT} default_server;
    listen [::]:${WEBDAV_PORT} default_server;
    root ${WEBROOT};

    location / {
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
        dav_methods             PUT DELETE MKCOL COPY MOVE;
        dav_ext_methods         PROPFIND OPTIONS;
        create_full_put_path    on;
        dav_access              user:rw;
    }

    auth_basic "Restricted area";
    auth_basic_user_file /app/htpasswd;
}
EOF

touch /app/htpasswd

# start nginx
nginx