#!/bin/sh
# ANODE session autostart runner (i3-style directives + drop-ins + XDG autostart, strict POSIX sh)
set -eu

: "${XDG_CONFIG_HOME:=$HOME/.config}"
: "${XDG_CONFIG_DIRS:=/etc/xdg}"
: "${XDG_CURRENT_DESKTOP:=ANODE}"
: "${ANODE_PREFIX:=/usr/local}"
: "${ANODE_XDG_AUTOSTART:=1}"

SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
CONF_DIR="$XDG_CONFIG_HOME/anode"

MODE="start"
EXPLICIT_CFG=""
PROFILE="${ANODE_SESSION_PROFILE:-}"
ENABLE_XDG="$ANODE_XDG_AUTOSTART"
DRY_RUN=0

usage() {
  cat <<'EOF'
Usage: anode-autostart [start|reload|list|check] [OPTIONS]

Commands:
  start           Run exec, exec_once, exec_always, autostart.d/, and XDG entries (default)
  reload          Run only exec_always directives (used on WM reload/restart)
  list            Print resolved autostart entries without executing them
  check           Validate declarative autostart files and includes (exit 0 on valid)

Options:
  --config FILE   Use FILE instead of ~/.config/anode/autostart
  --profile NAME  Load session profile overrides from autostart.NAME
  --no-xdg        Skip XDG /etc/xdg/autostart and ~/.config/autostart/*.desktop
  --dry-run       Print actions that would run without executing them
  -h, --help      Show this help
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    start|reload|list|check)
      MODE="$1"
      shift
      ;;
    --config)
      [ $# -ge 2 ] || { printf 'anode-autostart: --config requires a path\n' >&2; exit 2; }
      EXPLICIT_CFG="$2"
      shift 2
      ;;
    --config=*)
      EXPLICIT_CFG="${1#--config=}"
      shift
      ;;
    --profile)
      [ $# -ge 2 ] || { printf 'anode-autostart: --profile requires a name\n' >&2; exit 2; }
      PROFILE="$2"
      shift 2
      ;;
    --profile=*)
      PROFILE="${1#--profile=}"
      shift
      ;;
    --no-xdg)
      ENABLE_XDG=0
      shift
      ;;
    --dry-run)
      DRY_RUN=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      printf 'anode-autostart: unknown argument: %s\n' "$1" >&2
      exit 2
      ;;
  esac
done

if [ "$MODE" = "list" ]; then
  DRY_RUN=1
fi

find_sys_file() {
  _rel="$1"
  for _base in \
    "$ANODE_PREFIX/share/anode" \
    "$SCRIPT_DIR/../share/anode" \
    "$SCRIPT_DIR/../data"
  do
    if [ -r "$_base/$_rel" ]; then
      printf '%s\n' "$_base/$_rel"
      return 0
    fi
  done
  return 1
}

PRIMARY_CFG=""
if [ -n "$EXPLICIT_CFG" ]; then
  if [ ! -r "$EXPLICIT_CFG" ]; then
    printf 'anode-autostart: config file not readable: %s\n' "$EXPLICIT_CFG" >&2
    exit 1
  fi
  PRIMARY_CFG="$EXPLICIT_CFG"
elif [ -r "$CONF_DIR/autostart" ]; then
  PRIMARY_CFG="$CONF_DIR/autostart"
else
  PRIMARY_CFG="$(find_sys_file autostart || true)"
fi

PROFILE_CFG=""
if [ -n "$PROFILE" ]; then
  if [ -r "$CONF_DIR/autostart.$PROFILE" ]; then
    PROFILE_CFG="$CONF_DIR/autostart.$PROFILE"
  else
    PROFILE_CFG="$(find_sys_file "autostart.$PROFILE" || true)"
  fi
fi

# Extract executable basename from a shell command line for exec_once tracking
cmd_exec_base() {
  awk -v raw="$1" 'BEGIN {
    n = split(raw, a, /[ \t]+/)
    tok = ""
    for (i = 1; i <= n; i++) {
      if (a[i] == "") continue
      if (a[i] == "exec" || a[i] == "nohup" || a[i] == "env") continue
      if (a[i] ~ /^[A-Za-z_][A-Za-z0-9_]*=/) continue
      tok = a[i]
      break
    }
    gsub(/^["'\'']|["'\'']$/, "", tok)
    sub(/^.*\//, "", tok)
    print tok
  }'
}

is_proc_running() {
  _tgt="$1"
  [ -n "$_tgt" ] || return 1
  _self="$$"
  _my_uid="$(id -u)"
  _cands="$( (ps -eo uid=,pid=,comm=,args= 2>/dev/null || ps -ax -o uid=,pid=,comm=,args= 2>/dev/null || true) | awk -v tgt="$_tgt" -v self="$_self" -v myuid="$_my_uid" '
    {
      uid = $1; pid = $2; comm = $3; arg1 = $4
      if (uid != myuid || pid == self) next
      sub(/^.*\//, "", comm)
      sub(/^.*\//, "", arg1)
      if (comm == tgt || arg1 == tgt) {
        print pid
      }
    }
  ' )"
  [ -n "${_cands:-}" ] || return 1

  _cur_sid="${XDG_SESSION_ID:-}"
  _cur_dbus="${DBUS_SESSION_BUS_ADDRESS:-}"
  for _cpid in $_cands; do
    if [ -r "/proc/$_cpid/environ" ] && { [ -n "$_cur_sid" ] || [ -n "$_cur_dbus" ]; }; then
      _penv="$(tr '\0' '\n' < "/proc/$_cpid/environ" 2>/dev/null || true)"
      _p_sid="$(printf '%s\n' "$_penv" | awk 'substr($0, 1, 15) == "XDG_SESSION_ID=" { print substr($0, 16); exit }')"
      _p_dbus="$(printf '%s\n' "$_penv" | awk 'substr($0, 1, 25) == "DBUS_SESSION_BUS_ADDRESS=" { print substr($0, 26); exit }')"
      if [ -n "$_cur_sid" ] && [ -n "${_p_sid:-}" ] && [ "$_p_sid" != "$_cur_sid" ]; then
        continue
      fi
      if [ -n "$_cur_dbus" ] && [ -n "${_p_dbus:-}" ] && [ "$_p_dbus" != "$_cur_dbus" ]; then
        continue
      fi
      return 0
    fi
    return 0
  done
  return 1
}

launch_cmd() {
  _cmd="$1"
  (sh -c "$_cmd" </dev/null >/dev/null 2>&1 &)
}

run_declarative_files() {
  _strict=0
  [ "$MODE" = "check" ] && _strict=1

  if [ -z "$PRIMARY_CFG" ] && [ -z "$PROFILE_CFG" ]; then
    return 0
  fi

  _awk_err=0
  _parsed="$(awk -v conf_dir="$CONF_DIR" -v home_dir="$HOME" -v strict="$_strict" '
    function trim(s) {
      gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s)
      return s
    }
    function resolve_inc(p, base_dir,   out) {
      gsub(/^["'\'']|["'\'']$/, "", p)
      if (p ~ /^~\//) {
        out = home_dir "/" substr(p, 3)
      } else if (p ~ /^\//) {
        out = p
      } else {
        out = base_dir "/" p
      }
      return out
    }
    function parse_file(fpath, base_dir, depth,   nlines, i, raw, s, verb, rest, inc_p, inc_dir, rc) {
      if (depth > 8) {
        printf "anode-autostart: include depth exceeded at %s\n", fpath > "/dev/stderr"
        had_err = 1
        return
      }
      if (fpath in visited) {
        printf "anode-autostart: skipping cyclic/duplicate include: %s\n", fpath > "/dev/stderr"
        return
      }
      visited[fpath] = 1
      nlines = 0
      while ((rc = (getline raw < fpath)) > 0) {
        file_lines[fpath, ++nlines] = raw
      }
      close(fpath)
      if (rc < 0 && nlines == 0) {
        printf "anode-autostart: cannot read include file: %s\n", fpath > "/dev/stderr"
        if (strict) had_err = 1
        return
      }
      for (i = 1; i <= nlines; i++) {
        s = trim(file_lines[fpath, i])
        if (s == "" || substr(s, 1, 1) == "#") continue

        if (s ~ /^[A-Za-z0-9_]+[ \t]+/) {
          match(s, /^[A-Za-z0-9_]+/)
          verb = substr(s, 1, RLENGTH)
          rest = trim(substr(s, RLENGTH + 1))
        } else {
          verb = s
          rest = ""
        }

        if (verb == "exec" || verb == "exec_once" || verb == "exec_always") {
          if (rest ~ /^--no-startup-id([ \t]|$)/) {
            rest = trim(substr(rest, 16))
          }
          if (rest == "") {
            printf "anode-autostart: %s:%d: missing command for %s\n", fpath, i, verb > "/dev/stderr"
            had_err = 1
            continue
          }
          printf "%s\t%s\n", verb, rest
        } else if (verb == "include") {
          if (rest == "") {
            printf "anode-autostart: %s:%d: missing path for include\n", fpath, i > "/dev/stderr"
            had_err = 1
            continue
          }
          inc_p = resolve_inc(rest, base_dir)
          inc_dir = inc_p
          if (inc_dir ~ /\//) {
            sub(/\/[^\/]*$/, "", inc_dir)
            if (inc_dir == "") inc_dir = "/"
          } else {
            inc_dir = base_dir
          }
          parse_file(inc_p, inc_dir, depth + 1)
        } else {
          printf "anode-autostart: %s:%d: unknown directive: %s\n", fpath, i, verb > "/dev/stderr"
          had_err = 1
        }
      }
    }
    BEGIN {
      had_err = 0
      for (fi = 1; fi < ARGC; fi++) {
        fp = ARGV[fi]
        ARGV[fi] = ""
        if (fp != "") {
          bdir = fp
          if (bdir ~ /\//) {
            sub(/\/[^\/]*$/, "", bdir)
            if (bdir == "") bdir = "/"
          } else {
            bdir = conf_dir
          }
          parse_file(fp, bdir, 0)
        }
      }
      if (strict && had_err) exit 1
      exit 0
    }
  ' "$PRIMARY_CFG" "$PROFILE_CFG")" || _awk_err=1

  if [ "$_awk_err" != "0" ] && [ "$MODE" = "check" ]; then
    return 1
  fi
  if [ "$MODE" = "check" ]; then
    return 0
  fi

  _tab="$(printf '\t')"
  printf '%s\n' "$_parsed" | while IFS="$_tab" read -r _kind _cmd; do
    [ -n "${_kind:-}" ] || continue
    case "$MODE:$_kind" in
      reload:exec|reload:exec_once)
        continue
        ;;
    esac
    if [ "$_kind" = "exec_once" ] && [ "$DRY_RUN" != "1" ]; then
      _base="$(cmd_exec_base "$_cmd")"
      if is_proc_running "$_base"; then
        continue
      fi
    fi
    if [ "$DRY_RUN" = "1" ]; then
      printf '[%s] %s\n' "$_kind" "$_cmd"
    else
      launch_cmd "$_cmd"
    fi
  done
}

# Parse a .desktop autostart file and print:
#   HIDDEN          if Hidden=true
#   EXEC\t<try>\t<cmd> if runnable for XDG_CURRENT_DESKTOP
#   SKIP            otherwise
parse_desktop_entry() {
  _df="$1"
  awk -v cur_desk="$XDG_CURRENT_DESKTOP" '
    function trim(s) {
      gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s)
      return s
    }
    function list_matches(list_str, cur_str,   na, nb, a, b, i, j) {
      na = split(list_str, a, /[;:]/)
      nb = split(cur_str, b, /:/)
      for (i = 1; i <= na; i++) {
        if (a[i] == "") continue
        for (j = 1; j <= nb; j++) {
          if (b[j] != "" && tolower(a[i]) == tolower(b[j])) return 1
        }
      }
      return 0
    }
    BEGIN { in_de = 0; hidden = ""; only_in = ""; not_in = ""; try_exec = ""; exec_cmd = ""; term = "" }
    {
      s = trim($0)
      if (s == "" || substr(s, 1, 1) == "#") next
      if (substr(s, 1, 1) == "[") {
        in_de = (s == "[Desktop Entry]") ? 1 : 0
        next
      }
      if (!in_de) next
      eq = index(s, "=")
      if (eq <= 0) next
      k = trim(substr(s, 1, eq - 1))
      v = trim(substr(s, eq + 1))
      if (k == "Hidden") hidden = v
      else if (k == "OnlyShowIn") only_in = v
      else if (k == "NotShowIn") not_in = v
      else if (k == "TryExec") try_exec = v
      else if (k == "Exec") exec_cmd = v
      else if (k == "Terminal") term = v
    }
    END {
      if (tolower(hidden) == "true") {
        print "HIDDEN"
        exit
      }
      if (only_in != "" && !list_matches(only_in, cur_desk)) {
        print "SKIP"
        exit
      }
      if (not_in != "" && list_matches(not_in, cur_desk)) {
        print "SKIP"
        exit
      }
      if (exec_cmd == "") {
        print "SKIP"
        exit
      }
      gsub(/%%/, "\001", exec_cmd)
      gsub(/%[fFuUdDnNickvm]/, "", exec_cmd)
      gsub(/\001/, "%", exec_cmd)
      exec_cmd = trim(exec_cmd)
      if (exec_cmd == "") {
        print "SKIP"
        exit
      }
      if (tolower(term) == "true") {
        exec_cmd = "st -e " exec_cmd
      }
      printf "EXEC\t%s\t%s\n", try_exec, exec_cmd
    }
  ' "$_df"
}

check_try_exec() {
  _te="$1"
  [ -n "$_te" ] || return 0
  case "$_te" in
    */*) [ -x "$_te" ] && return 0 || return 1 ;;
    *) command -v "$_te" >/dev/null 2>&1 && return 0 || return 1 ;;
  esac
}

run_dir_dropins_and_xdg() {
  if [ "$MODE" = "reload" ] || [ "$MODE" = "check" ]; then
    return 0
  fi

  _seen_dropins=":"
  for _ddir in \
    "$CONF_DIR/autostart.d" \
    "$ANODE_PREFIX/share/anode/autostart.d" \
    "$SCRIPT_DIR/../share/anode/autostart.d" \
    "$SCRIPT_DIR/../data/autostart.d"
  do
    [ -d "$_ddir" ] || continue
    for _item in "$_ddir"/*; do
      [ -e "$_item" ] || continue
      _bn="$(basename "$_item")"
      case "$_seen_dropins" in
        *":$_bn:"*) continue ;;
      esac
      _seen_dropins="${_seen_dropins}${_bn}:"

      case "$_bn" in
        *.desktop)
          [ -r "$_item" ] || continue
          _res="$(parse_desktop_entry "$_item")"
          case "$_res" in
            EXEC*)
              _te="$(printf '%s\n' "$_res" | cut -f2)"
              _ecmd="$(printf '%s\n' "$_res" | cut -f3-)"
              if check_try_exec "$_te"; then
                if [ "$DRY_RUN" = "1" ]; then
                  printf '[desktop] %s\n' "$_ecmd"
                else
                  launch_cmd "$_ecmd"
                fi
              fi
              ;;
          esac
          ;;
        *)
          if [ -f "$_item" ] && [ -x "$_item" ]; then
            if [ "$DRY_RUN" = "1" ]; then
              printf '[script] %s\n' "$_item"
            else
              launch_cmd "$_item"
            fi
          fi
          ;;
      esac
    done
  done

  if [ "$ENABLE_XDG" = "1" ]; then
    _seen_xdg=":"
    _old_ifs="$IFS"
    IFS=:
    for _xbase in "$XDG_CONFIG_HOME" $XDG_CONFIG_DIRS; do
      [ -n "$_xbase" ] || continue
      _xdir="$_xbase/autostart"
      [ -d "$_xdir" ] || continue
      for _df in "$_xdir"/*.desktop; do
        [ -r "$_df" ] || continue
        _bn="$(basename "$_df")"
        case "$_seen_xdg" in
          *":$_bn:"*) continue ;;
        esac
        _seen_xdg="${_seen_xdg}${_bn}:"

        _res="$(parse_desktop_entry "$_df")"
        case "$_res" in
          EXEC*)
            _te="$(printf '%s\n' "$_res" | cut -f2)"
            _ecmd="$(printf '%s\n' "$_res" | cut -f3-)"
            if check_try_exec "$_te"; then
              if [ "$DRY_RUN" = "1" ]; then
                printf '[desktop] %s\n' "$_ecmd"
              else
                launch_cmd "$_ecmd"
              fi
            fi
            ;;
        esac
      done
    done
    IFS="$_old_ifs"
  fi
}

run_declarative_files || exit 1
run_dir_dropins_and_xdg
