#! /bin/sh

set -e

if [ -f /etc/gitlab-common/gitlab-common.conf ]; then
  . /etc/gitlab-common/gitlab-common.conf
else
  echo "Failed to find /etc/gitlab-common/gitlab-common.conf."
  exit 1
fi

. /etc/gitaly/gitaly-installer.conf

gitaly_defaults=/usr/lib/gitaly/gitaly.defaults

case "$1" in
  configure)
    . ${gitaly_defaults}

    # Download gitaly binaries
    . /usr/lib/gitaly/scripts/gitaly-download.sh

    # Create assets cache directory
    mkdir -p ${gitaly_cache}
    chown ${gitlab_user}: ${gitaly_cache}

    # Setup systemd service override
    service_path=/etc/systemd/system/gitaly.service.d
    mkdir -p ${service_path}
      if [ -e ${service_path}/override.conf ]; then
        echo "${service_path}/override.conf already exist"
        # Make sure only gitlab user is updated
        sed -i "s/^ *User=.*/User=${gitlab_user}/" ${service_path}/override.conf
      else
        printf "[Service]\nUser=${gitlab_user}\n" > ${service_path}/override.conf
      fi
      # Check if storage path exist and create if required
      export $(grep '^\s*path\s*=' /etc/gitaly/config.toml | sed 's/ //g' | sed 's/"//g' | sed "s/'//g" )
      if ! [ -d $path ] ; then runuser -u ${gitlab_user} -- sh -c 'mkdir $path'; fi

      # Manage tmpfiles.d/gitaly.conf via ucf
      cp ${gitaly_tmpfiles_example} ${gitaly_tmpfiles_private}
      sed -i "s/GITLAB_USER/${gitlab_user}/" ${gitaly_tmpfiles_private}
      echo "Registering ${gitaly_tmpfiles} via ucf"
      ucf --debconf-ok --three-way ${gitaly_tmpfiles_private} ${gitaly_tmpfiles}
      ucfr gitaly-installer ${gitaly_tmpfiles}

      install -d -o ${gitlab_user} -g ${gitlab_user} -m 0755 /run/gitlab/sockets/private

      if command -v systemd-tmpfiles >/dev/null; then
        systemd-tmpfiles --create ${gitaly_tmpfiles} || true
      fi
    ;;

    triggered)
    # Already handled
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;
    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

#DEBHELPER#
exit 0
