#!/usr/bin/env bash

set -e

if [[ -n "${DEBUG}" ]]; then
    set -x
fi

chown wodby:wodby "${APP_ROOT}"

declare -a dirs=(
    "${FILES_DIR}"
    "${FILES_DIR}/private"
    "${FILES_DIR}/public"
)

if [[ -n $1 && $1 =~ ^"${FILES_DIR}/" ]]; then
    dirs+=($1)
fi

for dir in "${dirs[@]}"; do
    mkdir -p "${dir}"
    chown www-data:www-data "${dir}"
    chmod 775 "${dir}"
done

if [[ -f /etc/crontabs/www-data ]]; then
    chown root:www-data /etc/crontabs/www-data
    chmod 660 /etc/crontabs/www-data
fi

if [[ -f /home/wodby/.ssh/id_rsa ]]; then
    chown wodby:wodby /home/wodby/.ssh/id_rsa
    chmod 600 /home/wodby/.ssh/id_rsa
fi

if [[ -f /root/.ssh/authorized_keys ]]; then
    cp /root/.ssh/authorized_keys /home/wodby/.ssh/authorized_keys
fi

if [[ -f /home/wodby/.ssh/authorized_keys ]]; then
    chown wodby:wodby /home/wodby/.ssh/authorized_keys
    chmod 600 /home/wodby/.ssh/authorized_keys
fi
