#!/bin/sh
#   
# pkgadd - Package install utility
# POSIX-compliant shell script for install, reinstall or upgrade packages
#

trap "interrupted" 1 2 3 15

export LC_ALL=C

# Resolve a file path to its absolute physical path without using external 'realpath'
get_realpath() {
    _dir=${1%/*}
    _file=${1##*/}
    # Use a subshell to avoid changing the current directory permanently
    (CDPATH= cd -P -- "$_dir" && printf '%s/%s\n' "$(pwd -P)" "$_file")
}

interrupted() {
    printf '\n'
    ret 1
}

msg() { printf "==> %s\n" "$1"; }
msgerr() { printf "ERROR: %s\n" "$1" >&2; }

help() {
    cat << 'EOF'
Usage:
  pkgadd [ <options> <package.spkg.txz> ]

Options:
  -u, --upgrade              upgrade package
  -r, --reinstall            reinstall package
  -c, --ignore-conflict      ignore conflict when installing package
  -v, --verbose              print files installed
  -h, --help                 show this help message
      --no-backup            skip backup when upgrading package
      --print-dbdir          print package database path
      --root=<path>          install to custom root directory
      
EOF
}

parse_opts() {
    if [ -z "$1" ]; then
        SHOWHELP=yes
    else
        while [ -n "$1" ]; do
            case $1 in
                -[!-]?*)
                    _rest=${1#-}; shift
                    while [ -n "$_rest" ]; do
                        _chr="${_rest%"${_rest#?}"}"
                        set -- "-$_chr" "$@"
                        _rest=${_rest#?}
                    done
                    continue ;;
            esac
            case $1 in
                -u | --upgrade)         UPGRADE_PKG=yes ;;
                -r | --reinstall)       REINSTALL_PKG=yes ;;
                -c | --ignore-conflict) IGNORE_CONFLICT=yes ;;
                -v | --verbose)         VERBOSE_INSTALL=yes ;;
                -h | --help)            SHOWHELP=yes ;;
                     --no-backup)       NO_BACKUP=yes ;;
                     --print-dbdir)     PRINTDBDIR=yes ;;
                     --root=*)          ROOT_DIR="${1#*=}" ;;
                     *.spkg.tar.*)      PKGNAME="$(get_realpath "$1")" ;;
                     *)                 msg "Invalid option! ($1)"; exit 1 ;;
            esac
            shift
        done
    fi
}

ret() {
    # Remove lock and all tmp files on exit
    rm -f "$ROOT_DIR/$LOCK_FILE" "$TMP_PKGADD" "$TMP_PKGINSTALL"
    exit "$1"
}

# Process options
parse_opts "$@"

SCRATCHPKG_DIR="var/lib/scratchpkg"
PKGDB_DIR="$SCRATCHPKG_DIR/db"
LOCK_FILE="$SCRATCHPKG_DIR/spkg.lock"

ROOT_DIR="${ROOT_DIR%/}" # Remove trailing slash

[ "$PRINTDBDIR" ] && {
    printf '%s/%s\n' "$ROOT_DIR" "$PKGDB_DIR"
    exit 0
}

# Show help page
if [ "$SHOWHELP" ] || [ -z "$PKGNAME" ]; then
    help
    exit 0
fi

[ -d "$ROOT_DIR/$PKGDB_DIR" ] || {
    msgerr "Package's database directory does not exist: $ROOT_DIR/$PKGDB_DIR"
    exit 1
}

# Check for root access
[ "$(id -u)" = "0" ] || {
    msgerr "Installing packages requires root access!"
    help
    exit 1
}

# Check for lock file
[ -f "$ROOT_DIR/$LOCK_FILE" ] && {
    msgerr "Cannot install/remove package simultaneously."
    msgerr "remove '$ROOT_DIR/$LOCK_FILE' if no install/remove package process running."
    exit 1
}

touch "$ROOT_DIR/$LOCK_FILE" 2>/dev/null || {
    msgerr "Cannot create lock file in '$ROOT_DIR/$LOCK_FILE'."
    exit 1
}

BASEPKGNAME="${PKGNAME##*/}"

# Check existence of package file
[ -f "$PKGNAME" ] || {
    msgerr "Package '$1' does not exist!"
    ret 1
}

noextname=${BASEPKGNAME%.spkg.tar.*}
release=${noextname##*-}
noextname=${noextname%-*}
version=${noextname##*-}
name=${noextname%-*}

# Get package information if installed
if [ -s "$ROOT_DIR/$PKGDB_DIR/$name" ]; then
    read -r iversion irelease < "$ROOT_DIR/$PKGDB_DIR/$name" # read first line
    ALREADYINSTALLED=yes
fi

if [ "$ALREADYINSTALLED" = "yes" ] && [ ! "$UPGRADE_PKG" ] && [ ! "$REINSTALL_PKG" ]; then
    printf "Package '%s' already installed. (%s-%s)\n" "$name" "$iversion" "$irelease"
    ret 0
fi

# Can't reinstall if not installed and can't upgrade if up-to-date
if [ "$UPGRADE_PKG" ] || [ "$REINSTALL_PKG" ]; then   
    if [ "$ALREADYINSTALLED" != "yes" ]; then
        msgerr "Package '$name' not installed."
        ret 1
    fi
    if [ "$UPGRADE_PKG" ]; then   
        if [ "$version-$release" = "$iversion-$irelease" ]; then
            printf "Package '%s' is up-to-date. (%s-%s)\n" "$name" "$iversion" "$irelease"
            ret 0
        fi
    fi
fi

TMP_PKGADD="$ROOT_DIR/$SCRATCHPKG_DIR/.tmp_pkgadd"
TMP_PKGINSTALL="$ROOT_DIR/$SCRATCHPKG_DIR/.tmp_pkginstall"

# Check integrity of package and save list file/dirs to install
# Note: POSIX 2024 standardized 'tar'. Flags are compliant.
tar -tvf "$PKGNAME" > "$TMP_PKGADD" 2>/dev/null || {
    msgerr "Package '$1' is corrupted!"
    ret 1
}

# Set operation whether install/upgrade/reinstall
opr=install
[ "$UPGRADE_PKG" ] && opr=upgrade
[ "$REINSTALL_PKG" ] && opr=reinstall
printf "%s: %s-%s-%s...\n" "$opr" "$name" "$version" "$release"

# Check for file conflict
if [ -z "$IGNORE_CONFLICT" ]; then
    # Determine if we need to exclude the current package (upgrade/reinstall)

    conflicts=0
    while IFS= read -r line; do
        # Remove .spkgnew suffix if present
        case "$line" in *.spkgnew) line=${line%.spkgnew} ;; esac
        # Check if file or symlink (including broken) exists in root
        if [ -e "$ROOT_DIR/$line" ] || [ -L "$ROOT_DIR/$line" ]; then
            # Skip if this file is already owned by the current package
	    if [ "$UPGRADE_PKG" ] || [ "$REINSTALL_PKG" ]; then
                if grep -Fxq "$line" "$ROOT_DIR/$PKGDB_DIR/$name" 2>/dev/null; then
                    continue  # belongs to this package, skip conflict
                fi
            fi
            # Find which installed package owns this file
            owner=$(grep -lFx "$line" "$ROOT_DIR/$PKGDB_DIR"/* 2>/dev/null | head -n1)
            [ -n "$owner" ] && owner=${owner##*/} || owner="(none)"        
            printf '%s %s\n' "$owner" "$line"
            conflicts=1
        fi
    # List package files (excluding directories ending in '/') to check for conflicts with awk command
    done << EOF
$(awk '!/\/$/{print $6}' "$TMP_PKGADD")
EOF

    if [ "$conflicts" -eq 1 ]; then
        msgerr "File conflict found!"
        ret 1
    fi
fi

rm -f "$TMP_PKGINSTALL"

# Extract package into ROOT_DIR
tar -xvhpf "$PKGNAME" -C "$ROOT_DIR"/ | while read -r line; do
    case "$line" in
      *.spkgnew)
        line="${line%.spkgnew}"
	# Handle spkgnew file in fresh install OR upgrade/reinstall when file is absent OR --no-backup is set
	if [ ! "$UPGRADE_PKG" ] && [ ! "$REINSTALL_PKG" ] || [ ! -e "$ROOT_DIR/$line" ] || [ "$NO_BACKUP" = yes ]; then
            cp --reflink=auto "$ROOT_DIR/$line".spkgnew "$ROOT_DIR/$line"
            rm -f "$ROOT_DIR/$line".spkgnew
        fi
	;;
    esac
    
    [ "$VERBOSE_INSTALL" ] && printf "extracted '%s'\n" "$line"
    printf '%s\n' "$line" >> "$TMP_PKGINSTALL"
done

# Remove old files from old package that do not exist in new package
if [ "$UPGRADE_PKG" ] || [ "$REINSTALL_PKG" ]; then
	# awk replacement for tail + tac (no POSIX)
	awk 'NR>1 { lines[n++] = $0 } END { while (n--) print lines[n] }' \
	    "$ROOT_DIR/$PKGDB_DIR/$name" | while read -r line; do
        case $line in
            */\[) ;;
            */) # Directory removal logic
                if grep "^$line$" "$ROOT_DIR/$PKGDB_DIR"/* "$TMP_PKGINSTALL" 2>/dev/null | grep -qv "$ROOT_DIR/$PKGDB_DIR/$name"; then
                     : # Do nothing if directory is used by another package
                else
                     # Manual verbose printing, as 'rmdir -v' is not POSIX
                     if [ "$VERBOSE_INSTALL" ]; then printf "removing directory '%s'\n" "$ROOT_DIR/$line"; fi
                     rmdir "$ROOT_DIR/$line" 2>/dev/null
                fi
                ;;
            *)  # File removal logic
                if ! grep -q "^$line$" "$TMP_PKGINSTALL"; then
                     # Manual verbose printing, as 'rm -v' is not POSIX
                     if [ "$VERBOSE_INSTALL" ]; then printf "removing '%s'\n" "$ROOT_DIR/$line"; fi
                     rm -f "$ROOT_DIR/$line"
                fi
                ;;
        esac
    done
fi

# Register package into database
# Use printf for safe output of version and release strings
printf '%s %s\n' "$version" "$release" > "$ROOT_DIR/$PKGDB_DIR/$name"
cat "$TMP_PKGINSTALL" >> "$ROOT_DIR/$PKGDB_DIR/$name"

# Running ldconfig
if [ -x "$ROOT_DIR"/sbin/ldconfig ]; then
    "$ROOT_DIR"/sbin/ldconfig -r "$ROOT_DIR"/
fi

ret 0

