#!/bin/bash
# panel-files — file manager for the hosting user's home folder. Paths are relative to /home/<user>.
#   panel-files list <dir>              entries, NUL-separated: type/linktype/size/mtime/mode/name   (max 5000)
#   panel-files stat <path>             type/size/mtime/mode/mime-encoding
#   panel-files read <file>             contents (text files up to 3 MB)
#   panel-files get <file>              contents (any file, for downloads)
#   panel-files write <file> [force]    new contents on stdin; .php files are syntax-checked first (exit 3 = not saved)
#   panel-files put <file>              upload: contents on stdin, replaces an existing file
#   panel-files mkdir <dir> | touch <file>
#   panel-files rename <path> <newpath>
#   panel-files chmod <path> <octal>
#   panel-files delete <path>           moves it to ~/.trash/<time>/… (inside the trash: deletes for good)
#   panel-files empty-trash
#   panel-files archive <dir>           the folder as .tar.gz on stdout
#   panel-files extract <archive>       unpack a .zip/.tar.gz next to it (existing files are kept)
#   panel-files on <server> <command…>  the same on a connected server (stdin/stdout are passed through)
# Every path must stay inside the home folder (links leading outside are refused) and every
# change runs as the hosting user, so files keep the right owner and root-only files stay untouchable.
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
U="$PANEL_USER"; HOMED="/home/$U"; TRASH="$HOMED/.trash"
[ -d "$HOMED" ] || die "no home folder $HOMED"
cd /
as_user() { runuser -u "$U" -- "$@"; }

# abs <rel> → absolute path inside the home folder (symlinks resolved), or die
abs() {
  local rel="${1:-}" p r
  [[ "$rel" != *$'\n'* ]] || die "bad path"
  rel="${rel#/}"; p="$HOMED${rel:+/$rel}"
  r=$(realpath -m -- "$p") || die "bad path"
  [[ "$r" == "$HOMED" || "$r" == "$HOMED/"* ]] || die "outside the home folder: /$rel"
  echo "$r"
}
# like abs, but the last part is not followed (rename/delete act on a link itself, not its target)
abs_nofollow() {
  local rel="${1#/}" dir base
  [ -n "$rel" ] || die "that is the home folder itself"
  [[ "$rel" != *$'\n'* ]] || die "bad path"
  base=$(basename -- "$rel"); dir=$(dirname -- "$rel"); [ "$dir" = . ] && dir=
  [[ "$base" != . && "$base" != .. ]] || die "bad name"
  dir=$(abs "$dir") || exit 1
  echo "$dir/$base"
}
valid_name() { [[ -n "$1" && "$1" != . && "$1" != .. && "$1" != */* && ${#1} -le 255 ]] || die "bad name: $1"; }

cmd="${1:-}"; shift || true
case "$cmd" in
  on)
    srv="${1:-}"; ip=$(node_ip "$srv") || die "unknown server: $srv"; shift
    [[ "${1:-}" =~ ^(list|stat|read|get|write|put|mkdir|touch|rename|chmod|delete|empty-trash|archive|extract)$ ]] || die "not allowed there: ${1:-}"
    exec ssh "${NODE_SSH_OPTS[@]}" "root@$ip" "/opt/panel/bin/panel-files $(printf '%q ' "$@")" ;;
  list)
    d=$(abs "${1:-}"); [ -d "$d" ] || die "not a folder: /${1:-}"
    { as_user find "$d" -mindepth 1 -maxdepth 1 -printf '%y/%Y/%s/%T@/%m/%f\0' || true; } | head -z -n 5000 ;;
  stat)
    f=$(abs "${1:-}"); [ -e "$f" ] || die "not found: /${1:-}"
    enc=-; [ -f "$f" ] && enc=$(as_user file -b --mime-encoding -- "$f" 2>/dev/null || echo -)
    printf '%s/%s\n' "$(as_user stat -c '%F/%s/%Y/%a' -- "$f")" "$enc" ;;
  read)
    f=$(abs "${1:-}"); [ -f "$f" ] || die "not a file: /${1:-}"
    [ "$(stat -c %s -- "$f")" -le 3145728 ] || die "too large to edit here (over 3 MB) — download it instead"
    [ "$(as_user file -b --mime-encoding -- "$f")" != binary ] || die "this is not a text file — download it instead"
    as_user cat -- "$f" ;;
  get)
    f=$(abs "${1:-}"); [ -f "$f" ] || die "not a file: /${1:-}"
    as_user cat -- "$f" ;;
  write|put)
    f=$(abs "${1:-}"); dir=$(dirname -- "$f"); [ -d "$dir" ] || die "folder does not exist"
    [ ! -d "$f" ] || die "that is a folder"
    tmp=$(as_user mktemp -p "$dir" ".panel-upload.XXXXXX") || die "cannot write in that folder"
    trap 'rm -f -- "$tmp"' EXIT
    as_user tee -- "$tmp" >/dev/null
    if [ "$cmd" = write ] && [[ "$f" == *.php ]] && [ "${2:-}" != force ]; then
      if ! out=$(as_user php -n -l "$tmp" 2>&1); then
        echo "$out" | grep -v '^Errors parsing' | sed "s#$tmp#$(basename -- "$f")#g" >&2; exit 3
      fi
    fi
    if [ -f "$f" ]; then as_user chmod --reference="$f" -- "$tmp" 2>/dev/null || true; else as_user chmod 644 -- "$tmp"; fi
    as_user mv -fT -- "$tmp" "$f"; trap - EXIT
    echo "Saved /${f#$HOMED/}" ;;
  mkdir)
    d=$(abs_nofollow "${1:-}"); valid_name "$(basename -- "$d")"; [ ! -e "$d" ] || die "already exists"
    as_user mkdir -m 755 -- "$d"; echo "Created folder /${d#$HOMED/}" ;;
  touch)
    f=$(abs_nofollow "${1:-}"); valid_name "$(basename -- "$f")"; [ ! -e "$f" ] || die "already exists"
    as_user sh -c 'umask 022; : > "$1"' sh "$f"; echo "Created file /${f#$HOMED/}" ;;
  rename)
    a=$(abs_nofollow "${1:-}") || exit 1; b=$(abs_nofollow "${2:-}") || exit 1; valid_name "$(basename -- "$b")"
    [ -e "$a" ] || [ -L "$a" ] || die "not found: /${1:-}"
    [ ! -e "$b" ] && [ ! -L "$b" ] || die "/${2#/} already exists"
    [ -d "$(dirname -- "$b")" ] || die "target folder does not exist"
    [[ "$b/" != "$a/"* ]] || die "cannot move a folder into itself"
    as_user mv -nT -- "$a" "$b"; echo "Renamed to /${b#$HOMED/}" ;;
  chmod)
    f=$(abs "${1:-}"); [[ "${2:-}" =~ ^[0-7]{3}$ ]] || die "permissions: three digits like 644 or 755"
    as_user chmod "$2" -- "$f"; echo "/${f#$HOMED/} is now $2" ;;
  delete)
    f=$(abs_nofollow "${1:-}"); [ -e "$f" ] || [ -L "$f" ] || die "not found: /${1:-}"
    [ "$f" != "$TRASH" ] || die "use \"Empty trash\" for the trash folder"
    rel="${f#$HOMED/}"
    if [[ "$f" == "$TRASH/"* ]]; then as_user rm -rf -- "$f"; echo "Deleted /$rel for good"; exit 0; fi
    dest="$TRASH/$(date +%Y-%m-%d_%H%M%S)/$rel"
    as_user mkdir -p -m 700 -- "$TRASH"; as_user mkdir -p -- "$(dirname -- "$dest")"
    [ ! -e "$dest" ] || dest="$dest.$RANDOM"
    as_user mv -T -- "$f" "$dest"; echo "Moved /$rel to the trash (~/.trash)" ;;
  archive)   # a folder as .tar.gz on stdout (for downloads)
    d=$(abs "${1:-}"); [ -d "$d" ] || die "not a folder: /${1:-}"
    [ "$d" != "$HOMED" ] || die "pick a folder inside the home folder"
    as_user nice -n 10 tar -C "$(dirname -- "$d")" -czf - -- "$(basename -- "$d")" ;;
  extract)   # unpack a .zip / .tar.gz / .tgz / .tar next to it; files that already exist are kept
    f=$(abs "${1:-}"); [ -f "$f" ] || die "not a file: /${1:-}"; dir=$(dirname -- "$f")
    case "${f,,}" in
      *.zip) as_user python3 - "$f" "$dir" <<'PYX'
import os, sys, zipfile
z = zipfile.ZipFile(sys.argv[1]); dest = sys.argv[2]; n = kept = 0
if sum(i.file_size for i in z.infolist()) > 20 * 1024**3: sys.exit('error: the archive unpacks to more than 20 GB')
for i in z.infolist():
    t = os.path.join(dest, i.filename)
    if not i.is_dir() and os.path.lexists(t): kept += 1; continue
    z.extract(i, dest); n += 0 if i.is_dir() else 1
    if not i.is_dir():
        mode = (i.external_attr >> 16) & 0o777
        os.chmod(os.path.join(dest, i.filename), 0o755 if mode & 0o100 else 0o644)
print('Unpacked %d files' % n + (', kept %d that already existed' % kept if kept else ''))
PYX
        ;;
      *.tar.gz|*.tgz|*.tar|*.tar.bz2|*.tar.xz)
        n=$(as_user tar -C "$dir" --skip-old-files --no-same-owner --no-same-permissions -xvf "$f" | grep -vc '/$' || true); echo "Unpacked $n files (existing files were kept)" ;;
      *) die "can unpack .zip, .tar.gz, .tgz and .tar files" ;;
    esac ;;
  empty-trash)
    [ -d "$TRASH" ] || { echo "The trash is already empty"; exit 0; }
    sz=$(du -sh "$TRASH" 2>/dev/null | cut -f1)
    as_user find "$TRASH" -mindepth 1 -delete 2>/dev/null || as_user rm -rf -- "$TRASH"/* "$TRASH"/.[!.]* 2>/dev/null || true
    echo "Emptied the trash ($sz)" ;;
  *) sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;;
esac
