#!/usr/bin/env bash

set -euo pipefail

DOTFILES_URI="${DOTFILES_URI}"
DOTFILES_USER="${DOTFILES_USER}"
DOTFILES_BRANCH="${DOTFILES_BRANCH}"

# Validate DOTFILES_URI to prevent command injection (defense in depth)
if [ -n "$DOTFILES_URI" ]; then
  # shellcheck disable=SC2250
  if [[ "$DOTFILES_URI" =~ [^a-zA-Z0-9._/:@-] ]]; then
    echo "ERROR: DOTFILES_URI contains invalid characters" >&2
    exit 1
  fi
  if ! [[ "$DOTFILES_URI" =~ ^(https?://|ssh://|git@|git://) ]]; then
    echo "ERROR: DOTFILES_URI must be a valid repository URL (https://, http://, ssh://, git@, or git://)" >&2
    exit 1
  fi
fi

# shellcheck disable=SC2157
if [ -n "$${DOTFILES_URI// }" ]; then
  if [ -z "$DOTFILES_USER" ]; then
    DOTFILES_USER="$USER"
  fi

  if [ -n "$DOTFILES_BRANCH" ]; then
    echo "✨ Applying dotfiles for user $DOTFILES_USER from branch $DOTFILES_BRANCH"
  else
    echo "✨ Applying dotfiles for user $DOTFILES_USER"
  fi

  if [ "$DOTFILES_USER" = "$USER" ]; then
    if [ -n "$DOTFILES_BRANCH" ]; then
      coder dotfiles "$DOTFILES_URI" --branch "$DOTFILES_BRANCH" -y 2>&1 | tee ~/.dotfiles.log
    else
      coder dotfiles "$DOTFILES_URI" -y 2>&1 | tee ~/.dotfiles.log
    fi
  else
    if command -v getent > /dev/null 2>&1; then
      DOTFILES_USER_HOME=$(getent passwd "$DOTFILES_USER" | cut -d: -f6)
    else
      DOTFILES_USER_HOME=$(awk -F: -v user="$DOTFILES_USER" '$1 == user {print $6}' /etc/passwd)
    fi
    if [ -z "$DOTFILES_USER_HOME" ]; then
      echo "ERROR: Could not determine home directory for user $DOTFILES_USER" >&2
      exit 1
    fi

    CODER_BIN=$(command -v coder)
    if [ -n "$DOTFILES_BRANCH" ]; then
      sudo -u "$DOTFILES_USER" "$CODER_BIN" dotfiles "$DOTFILES_URI" --branch "$DOTFILES_BRANCH" -y 2>&1 | tee "$DOTFILES_USER_HOME/.dotfiles.log"
    else
      sudo -u "$DOTFILES_USER" "$CODER_BIN" dotfiles "$DOTFILES_URI" -y 2>&1 | tee "$DOTFILES_USER_HOME/.dotfiles.log"
    fi
  fi
fi

POST_CLONE_SCRIPT="${POST_CLONE_SCRIPT}"

if [ -n "$POST_CLONE_SCRIPT" ]; then
  echo "Running post-clone script..."
  POST_CLONE_TMP=$(mktemp)
  echo "$POST_CLONE_SCRIPT" | base64 -d > "$POST_CLONE_TMP"
  chmod +x "$POST_CLONE_TMP"
  $POST_CLONE_TMP
  rm "$POST_CLONE_TMP"
fi
