#!/bin/bash
set -eu
### --help Info: инициализация прав доступа и nss_wrapper в зависимости от uid.
### --help Usage: source /opt/bin/eva_init_access.sh
### --help Example: source /opt/bin/eva_init_access.sh
. /opt/fox_utils/crab_sys.sh

declare UID_ GID
UID_="$(id -u)"
GID="$(id -g)"

declare REDIS_SERVER_ENABLED POSTGRESQL_ENABLED NGINX_ENABLED
if [[ -f /opt/CONFIG ]]; then
	source /opt/CONFIG
fi


postgres_root() {
	# /var/lib/postgresql must be owned by postgres ang has permissions 0700
	if [[ $(stat -c %u /var/lib/postgresql/) != $(id -u postgres) ]]; then
		chown -R postgres /var/lib/postgresql/
	fi
	if [[ $(stat -c %a /var/lib/postgresql/) != 700 ]]; then
		chmod -R 0700 /var/lib/postgresql/
	fi
	return 0
}

postgres_non_root() {
	if [[ -e /var/run/postgresql ]]; then
		if [[ $(stat -c %u /var/run/postgresql/) != $(id -u postgres) ]]; then
			mv /var/run/postgresql /var/run/postgresql.bk
			# may be some warnings
			rsync -a /var/run/postgresql.bk/ /var/run/postgresql || true
			rm -rf --one-file-system /var/run/postgresql.bk
		fi
	else
		install -d -m 2770 /var/run/postgresql
	fi

	if [[ $(stat -c %u /mnt/shared/postgresql/) != $(id -u postgres) ]]; then
		mv /mnt/shared/postgresql /mnt/shared/postgresql.bk
		# may be some warnings
		rsync -a /mnt/shared/postgresql.bk/ /mnt/shared/postgresql || true
		rm -rf --one-file-system /mnt/shared/postgresql.bk
	fi

	if [[ $(stat -c %a /var/lib/postgresql/) != 700 ]]; then
		chmod -R 0700 /var/lib/postgresql/
	fi
	return 0
}

eva_git_ssh_permissions() {
	local githome ssh_dir key
	githome="/mnt/shared/eva_git/githome"
	ssh_dir="$githome/.ssh"

	[[ $(stat -c %a $ssh_dir) != 700 ]] && chmod 0700 "$ssh_dir"

	for key in $(find "$ssh_dir" -mindepth 1 -type f -iname 'id*' ! -iname '*.pub'); do
		[[ $(stat -c %a $key) != 600 ]] && chmod 0600 "$key"
	done

	for key in $(find "$ssh_dir" -mindepth 1 -type f ! -iname '*.pub'); do
		[[ $(stat -c %a $key) != 644 ]] && chmod 0644 "$key"
	done

	if [[ -f "$ssh_dir/authorized_keys" && $(stat -c %a "$ssh_dir/authorized_keys") != 600 ]]; then
		chmod 0600 "$ssh_dir/authorized_keys"
	fi

	if [[ -f "$ssh_dir/config" && $(stat -c %a "$ssh_dir/config") != 640 ]]; then
		chmod 0640 "$ssh_dir/config"
	fi

	[[ $(stat -c %a $githome) != 740 ]] && chmod 0740 "$githome"
	return 0
}


if [[ $UID_ = 0  ]]; then
	if [ "${POSTGRESQL_ENABLED:-TRUE}" = 'TRUE' ]; then
		postgres_root
	fi
else
	if [ "${POSTGRESQL_ENABLED:-TRUE}" = 'TRUE' ]; then
		postgres_non_root
	fi
fi

eva_git_ssh_permissions

exit 0
