#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-05-05; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.live.builder.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.live.builder
# SPDX-Security-Contact: security@coresecret.eu

########################################################################################### Bash
alias clear="printf '\033c'"
alias c='clear'
alias q='exit'

########################################################################################### Chrony
alias cytr='echo "tracking -a -v" | chronyc'
alias cysd='echo "selectdata -a -v" | chronyc'
alias cyss='echo "sourcestats -a -v" | chronyc'

########################################################################################### fail2ban & ufw
alias f2ball='fail2ban-client status'
alias f2bubn='fail2ban-client unban --all'
alias f2bufw='fail2ban-client status ufw'
alias usn='ufw status numbered'
alias usv='ufw status verbose'

########################################################################################### ls
alias ls='eza --group-directories-first --icons=always --oneline --long --all --group --header --blocksize --inode --flags --binary --octal-permissions --total-size --sort extension'
alias lsf='eza --group-directories-first --icons=always --oneline --long --all --absolute --group --header --blocksize --inode --flags --binary --octal-permissions --total-size --sort extension'
alias lss='eza --group-directories-first --icons=always --oneline --long --all --absolute --group --header --blocksize --inode --flags --binary --octal-permissions --total-size --sort extension --extended'
alias la='ls'
alias ll=ls
alias l=ls

########################################################################################### Package Management
alias aptac='apt autoclean'
alias aptap='apt autopurge'
alias aptar='apt autoremove'
alias aptcheck='apt-get check'
alias aptdep='apt-cache depends'
alias aptdl='apt-get install --download-only'
alias aptfug='apt full-upgrade'
alias aptupd='apt update'
alias aptupg='apt upgrade'
alias apti='apt install'
alias aptp='apt purge'
alias aptpp='dpkg --purge'
alias aptr='apt remove'
alias aptse='apt search'
alias aptsh='apt show'
alias aptimage='apt-cache search linux-image | grep linux-image | grep amd64 | grep -v "dbg" | grep -v "meta-package" | grep -v "cloud" | grep -v "PREEMPT"'

########################################################################################### Readability
alias df='df -h'
alias free='free -m'
alias mkdir='mkdir -pv'

########################################################################################### Service restart
alias rsban='systemctl restart fail2ban'
alias rsweb='systemctl restart nginx php8.4-fpm redis'

########################################################################################### System maintaining
alias boot='reboot -h now'
alias cscan='clamscan -r --bell -i'
alias chkhvg='haveged -n 0 | dieharder -g 200 -a'
alias dev='lsblk -o NAME,MAJ:MIN,FSTYPE,FSVER,SIZE,UUID,MOUNTPOINT,PATH'
alias i='echo "$(whoami) @ $(uname -a)"'
alias ipunused='iptables -L -v -n'
alias jboot='journalctl --boot=0'
alias lsadt='lynis audit system --auditor Centurion_Intelligence_Consulting_Agency'
alias lsadtdoc='lynis audit system --auditor Centurion_Intelligence_Consulting_Agency > /root/lynis-$(date +%F_%H-%M-%S).txt 2>&1'
alias n='nano'
alias nstat='netstat -tlpnvWa'
alias s='sudo -i'
alias sas='systemd-analyze security'
alias shut='shutdown -h now'
alias ssa='systemctl status'
alias ssf='systemctl status --failed'
alias sysdr='systemctl daemon-reload'
alias syses='systemctl edit'
alias sysliboot='systemctl list-unit-files --state=enabled --type=service'
alias syslirun='systemctl list-units --type=service --state=running'
alias sysrl='systemctl reload'
alias sysrs='systemctl restart'
alias syssp='systemctl stop'
alias sysst='systemctl start'
alias v='nvim'
alias whatdelete='lsof | grep deleted'
alias whatimage='dpkg --list | grep linux-image'
alias whatpurge='dpkg --get-selections | grep deinstall'

########################################################################################### Functions

#######################################
# Generates Secure (/dev/random) Passwords
# Arguments:
#    Length of Password, e.g., 32, and --base64 in case of encoding in BASE64.
#######################################
# shellcheck disable=SC2317
genpasswd() {
  declare -i length=32
  declare -i usebase64=0

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --base64)
        usebase64=1
        ;;
      '' | *[!0-9]*) ;;
      *)
         length="$1"
        ;;
    esac
    shift
  done

  declare passwd
  # shellcheck disable=SC2312
  passwd=$(tr -dc 'A-Za-z0-9_' < /dev/random | head -c "${length}")

  if [[ ${usebase64} -eq 1 ]]; then
    echo -n "${passwd}" | base64
  else
    echo "${passwd}"
  fi
}

#######################################
# Generates Secure (/dev/random) Passwords.
# Arguments:
#   none
#######################################
# shellcheck disable=SC2317
genpasswdhash() {
  declare salt
  # shellcheck disable=SC2312
  salt=$(tr -dc 'A-Za-z0-9' < /dev/random | head -c 16)
  mkpasswd --method=sha-512 --salt="${salt}" --rounds=8388608
}

#######################################
# Outputs a 16-character random printable string
# Arguments:
#   None
#######################################
genstring() {
  # shellcheck disable=SC2312
  (haveged -n 1000 -f - 2>/dev/null | tr -cd '[:graph:]' | fold -w 16 && echo ) | head
}

#######################################
# Wrapper for secure curl
# Globals:
#   CRED
#   CRES
#   NL
# Arguments:
#   1: URL from which to download a specific file
#   2: /path/to/file to be saved to
# Returns:
#   0: Download successful
#   1: Usage error
#   2: Download failure
#######################################
scurl() {
  if [[ $# -ne 2 ]]; then
    printf "%b❌ Error: Usage: scurl <URL> <path/to/file>. %b%b" "${CRED}" "${CRES}" "${NL}" >&2
    return 1
  fi
  declare url="$1"
  declare output_path="$2"
  if ! curl --doh-url "https://dns01.eddns.eu/dns-query" \
            --doh-cert-status \
            --tlsv1.3 \
            -sSf \
            -o "${output_path}" \
            "${url}"
  then
    printf "%b❌ Error: Download failed for URL: '%s'. %b%b" "${CRED}" "${url}" "${CRES}" "${NL}" >&2
    return 2
  fi
  return 0
}

#######################################
# Wrapper for secure wget
# Globals:
#   CRED
#   CRES
#   NL
# Arguments:
#   1: URL from which to download a specific file
#   2: /path/to/file to be saved to
# Returns:
#   0: Download successful
#   1: Usage error
#   2: Download failure
#######################################
swget() {
  if [[ $# -ne 2 ]]; then
    printf "%b❌ Error: Usage: swget <URL> <path/to/file>. %b%b" "${CRED}" "${CRES}" "${NL}" >&2
    return 1
  fi
  declare url="$1"
  declare output_path="$2"
  mkdir -p "$(dirname "${output_path}")"
  if ! wget --show-progress \
            --no-clobber \
            --https-only \
            --secure-protocol=TLSv1_3 \
            -qO "${output_path}" \
            "${url}"
  then
    printf "%b❌ Error: Download failed for URL: '%s'. %b%b" "${CRED}" "${url}" "${CRES}" "${NL}" >&2
    return 2
  fi
  return 0
}

#######################################
# Wrapper for loading CISS hardened Kernel Parameters.
# Arguments:
#   None
#######################################
sysp() {
  sysctl -p /etc/sysctl.d/99_local.hardened
  # shellcheck disable=SC2312
  sysctl -a | grep -E 'kernel|vm|net' >| /var/log/sysctl_check"$(date +"%Y-%m-%d_%H:%M:%S")".log
}

#######################################
# Wrapper for tree
# Arguments:
#   1: Depth of Directory Listing
#######################################
trel() {
  declare depth=${1:-3}

  if ! [[ "${depth}" =~ ^[0-9]+$ ]]; then
    echo "Error: '${depth}' is not a valid depth. Please provide a positive integer." >&2
    return 2
  fi

  if ! command -v eza >/dev/null 2>&1; then
    echo "Error: 'eza' is not installed." >&2
    return 1
  fi

  (( $# > 0 )) && shift

  eza --tree \
    --level="${depth}" \
    --group-directories-first \
    --icons=auto \
    --color=always \
    --long \
    --no-permissions \
    --no-user \
    --no-time \
    "$@"

  return 0
}

#######################################
# Wrapper for package and path to bin.
# Arguments:
#   1: Program
#######################################
whichpackage() {
  if ! command -v "$1" >/dev/null 2>&1; then
    printf '%b❌ Error: Program '%s' not found. %b%b' "${CRED}" "$1" "${CRES}" "${NL}" >&2
    exit 1
  fi
  # shellcheck disable=SC2230,SC2312
  dpkg -S "$(which "$1")"
}

#######################################
# Wrapper for Diskspace used in Path.
# Arguments:
#   1: Path (defaults /var)
#   2: Depth (defaults 1)
#   3: Number of Entries (defaults 16)
#######################################
whichused() {
  # shellcheck disable=SC2312
  du -h --max-depth="${2:-1}" "${1:-/var}" | sort -hr | head -n "${3:-16}"
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
