#!/bin/sh

# Set permissions on deploy dirs so they can be used by deploy and/or app user

# Exit on errors
set -e

# Environment vars
# DESTDIR, prefix for target files, optional

# Config vars
DEPLOY_DIR="${DEPLOY_DIR:-"<%= deploy_dir %>"}"
CURRENT_DIR="${CURRENT_DIR:-"<%= current_dir %>"}"
DEPLOY_USER="${DEPLOY_USER:-"<%= deploy_user %>"}"
DEPLOY_GROUP="${DEPLOY_GROUP:-"<%= deploy_group %>"}"
APP_USER="${APP_USER:-"<%= app_user %>"}"
APP_GROUP="${APP_GROUP:-"<%= app_group %>"}"

# Allow deploy user to manage deploy dir
chown $DEPLOY_USER:$APP_GROUP "$DEPLOY_DIR"
chmod 750 "$DEPLOY_DIR"

# Make programs in bin executable by deploy and app users
mkdir -p "$DEPLOY_DIR/bin"
chown -R $DEPLOY_USER:$APP_GROUP "$DEPLOY_DIR/bin"
chmod -R 750 "$DEPLOY_DIR/bin"

# Make programs in release executable by app group
chown -R $DEPLOY_USER:$APP_GROUP "$CURRENT_DIR"
find -H $CURRENT_DIR -executable -type f -exec chmod g+x {} \;

# Make deploy etc writable by app user
# mkdir -p "$DEPLOY_DIR/etc"
# chown -R $DEPLOY_USER:$APP_GROUP "$DEPLOY_DIR/etc"
# chmod -R 770 "$DEPLOY_DIR/etc"

# Make release tmp writable by app user
<%= case release_system do %>
<% :mix -> %>
# RELEASE_TMP="${CURRENT_DIR}/tmp"
<% :distillery -> %>
# RELEASE_TMP="${CURRENT_DIR}/var"
<% end %>
# mkdir -p "$RELEASE_TMP"
# chmod -R 770 "$RELEASE_TMP"
# chown -R $DEPLOY_USER:$APP_GROUP "$RELEASE_TMP"
