#!/usr/bin/env bash
# Exercise 1: permission math (easy)
# Run with: bash linux_filesystem_and_permissions_exercise_1.sh
#
# STEP 1: octal_to_symbolic MODE — "750" → "rwxr-x---", "644" → "rw-r--r--"
#         Also support 4-digit modes with special bits: "4755" → "rwsr-xr-x",
#         "1777" → "rwxrwxrwt", "2750" → "rwxr-s---"; uppercase S/T when the
#         execute bit underneath is NOT set ("4644" → "rwSr--r--")
# STEP 2: symbolic_to_octal PERMS — "rwxr-x---" → "750" (9 chars, no special bits)
# STEP 3: apply_umask UMASK TYPE — default mode for a new file (666) or dir (777)
#         after the umask: apply_umask 022 file → "644", apply_umask 027 dir → "750"
# STEP 4: can_access PERMS OWNER GROUP USER USER_GROUPS WANT
#         Decide like the kernel: pick EXACTLY ONE class (owner if USER==OWNER,
#         else group if GROUP is in the space-separated USER_GROUPS, else other),
#         then print "yes" if that class has the WANT bit (r, w or x), else "no".
#         Ignore root and ACLs.

set -uo pipefail

octal_to_symbolic() {
  # TODO
  :
}

symbolic_to_octal() {
  # TODO
  :
}

apply_umask() {
  # TODO: hint — base & ~umask, per digit
  :
}

can_access() {
  # TODO
  :
}

# --- self-check: do not modify below this line ---
all_ok=true
check() {
  if [[ "$2" == "$3" ]]; then echo "ok   $1"; else echo "FAIL $1 (got '$2', expected '$3')"; all_ok=false; fi
}

check "750"  "$(octal_to_symbolic 750)"  "rwxr-x---"
check "644"  "$(octal_to_symbolic 644)"  "rw-r--r--"
check "600"  "$(octal_to_symbolic 600)"  "rw-------"
check "4755" "$(octal_to_symbolic 4755)" "rwsr-xr-x"
check "4644" "$(octal_to_symbolic 4644)" "rwSr--r--"
check "2750" "$(octal_to_symbolic 2750)" "rwxr-s---"
check "1777" "$(octal_to_symbolic 1777)" "rwxrwxrwt"
check "1776" "$(octal_to_symbolic 1776)" "rwxrwxrwT"
check "rwxr-x---" "$(symbolic_to_octal rwxr-x---)" "750"
check "rw-r-----" "$(symbolic_to_octal rw-r-----)" "640"
check "r--------" "$(symbolic_to_octal r--------)" "400"
check "umask 022 file" "$(apply_umask 022 file)" "644"
check "umask 027 dir"  "$(apply_umask 027 dir)"  "750"
check "umask 077 file" "$(apply_umask 077 file)" "600"
check "owner can read"          "$(can_access rw-r----- alice devs alice 'alice devs' r)" "yes"
check "group can read"          "$(can_access rw-r----- alice devs bob 'bob devs' r)" "yes"
check "group cannot write"      "$(can_access rw-r----- alice devs bob 'bob devs' w)" "no"
check "other cannot read"       "$(can_access rw-r----- alice devs eve 'eve' r)" "no"
check "owner class does not fall through" "$(can_access ---rwxrwx alice devs alice 'alice devs' r)" "no"
check "other can execute"       "$(can_access rwx--x--x root root eve 'eve' x)" "yes"

if $all_ok; then echo "PASS"; else echo "FAIL"; fi
