#!/bin/bash
#
# clean-chroot-manager by graysky
#

# shellcheck disable=1090

VERS='2.226'
PKG='clean-chroot-manager'
SKEL="/usr/share/$PKG/ccm.skel"

### Begin insert of Arch script
# Avoid any encoding problems
export LANG=C

# check if messages are to be printed using color
unset ALL_OFF BOLD BLUE GREEN RED YELLOW
if [[ -t 2 ]]; then
  # prefer terminal safe colored and bold text when tput is supported
  if tput setaf 0 &>/dev/null; then
    ALL_OFF="$(tput sgr0)"
    BOLD="$(tput bold)"
    BLUE="${BOLD}$(tput setaf 4)"
    GREEN="${BOLD}$(tput setaf 2)"
    RED="${BOLD}$(tput setaf 1)"
    YELLOW="${BOLD}$(tput setaf 3)"
  else
    ALL_OFF="\e[1;0m"
    BOLD="\e[1;1m"
    BLUE="${BOLD}\e[1;34m"
    GREEN="${BOLD}\e[1;32m"
    RED="${BOLD}\e[1;31m"
    YELLOW="${BOLD}\e[1;33m"
  fi
fi
readonly ALL_OFF BOLD BLUE GREEN RED YELLOW

### End insert of Arch script

if [[ -z "$SUDO_USER" ]]; then
  if logname &>/dev/null; then
    USER=$(logname)
  fi
elif [[ "$SUDO_USER" = "root" ]]; then
  mesg="Cannot determine your username."
  echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
else
  USER="$SUDO_USER"
fi

HOMEDIR="$(getent passwd "$USER" | cut -d: -f6)"

# allow user to override from cli thus using multiple files as needed
XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOMEDIR/.config}"
CFGFILE=${CFGFILE:-$XDG_CONFIG_HOME/$PKG.conf}

# dependency checks probably not needed but they do not hurt
if ! command -v mkarchroot >/dev/null 2>&1; then
  mesg="devtools is required to use this script."
  echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
fi

check_config() {
  if [[ $EUID -ne 0 ]]; then
    local mesg="This script must be called as root."
    echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
  fi

  if [[ ! -f $SKEL ]]; then
    local mesg="$SKEL is missing.  Reinstall this package to continue."
    echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
  fi

  if [[ ! -f "$CFGFILE" ]]; then
    echo -e "${BOLD}------------------------------------------------------------${ALL_OFF}"
    echo -e "${BOLD} No config file found so creating a fresh one in:${ALL_OFF}"
    echo -e "${BOLD}${BLUE} $XDG_CONFIG_HOME/$PKG.conf${ALL_OFF}"
    echo
    echo -e "${BOLD} Edit this file before invoking $PKG again.${ALL_OFF}"
    echo -e "${BOLD}------------------------------------------------------------${ALL_OFF}"
    su -c "install -Dm644 $SKEL $CFGFILE" "$USER"
    CORES=$(( $(nproc --all) + 1 ))
    sed -i "/^THREADS=/ s,9,$CORES," "$XDG_CONFIG_HOME/$PKG.conf"
    exit 0
  else
    . "$CFGFILE"

    # parse config file for correctness
    if [[ ! -d "$CHROOTPATH64" ]]; then
      mkdir -p "$CHROOTPATH64" || {
      local mesg="Invalid CHROOTPATH64 defined in $CFGFILE"
      echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
    }
    fi

    if ! [[ "$THREADS" =~ ^[0-9]+$ ]]; then
      local mesg="Invalid setting for THREADS defined in $SKEL"
      echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
    fi
  fi

  if [[ -n "$DISTCC_THREADS" ]]; then
    if ! [[ "$DISTCC_THREADS" =~ ^[0-9]+$ ]]; then
      local mesg="Invalid setting for DISTCC_THREADS defined in $SKEL"
      echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
    fi
  fi

  # ccache must be present on the host system or else devtools scripts
  # will throw an error.
  # probably redundant to add a check here but might be more straight forward
  # for users if we do... will leave it out for now.

  if [[ -z ${CCACHE_DIR+x} ]]; then
    # no ccache is being used
    true
  else
    # make sure we have a dir with correct permissions for ccache to use
    if  [[ ! -d "$CCACHE_DIR" ]]; then
      local mesg="Invalid CCACHE_DIR defined in $CFGFILE"
      echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
    fi

    if sudo -u "$USER" -H sh -c "[ ! -w \"$CCACHE_DIR\" ]"; then
      local mesg="$USER has no write permissions on $CCACHE_DIR"
      echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
    fi
  fi

  # identify status of testing repo
  PACFILE="$CHROOTPATH64/root/etc/pacman.conf"
  if [[ -f "$PACFILE" ]]; then
    if grep -q '^#\[core-testing\]' "$PACFILE"; then
      # testing repo is not enabled
      export TESTING="Disabled"
    elif grep -q '^\[core-testing\]' "$PACFILE"; then
      # testing repo is enabled
      export TESTING="Enabled"
    fi
  fi

  # if user defined a trailing slash remove it here
  if [[ -n "$REPO" ]]; then
    REPO="${REPO%/}"
    # check for external path
    if sudo -u "$USER" -H sh -c "[ ! -w \"$REPO\" ]"; then
      local mesg="User $USER has no write permissions on $REPO"
      echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
    fi
  else
    REPO="${CHROOTPATH64%/}/root/repo"
    export INTERNAL_REPO=1
  fi

  if [[ -z "$REPO_NAME" ]]; then
    REPO_NAME="chroot_local"
  fi
}

check_buildroot() {
  if [[ ! -f "$CHROOTPATH64"/root/.arch-chroot ]]; then
    local mesg="No buildroot found; create one using the 'c' option and try again."
    echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
  fi
}

check_active() {
  if pidof -q -x makechrootpkg; then
    mesg="Active build detected.  Try again when not building."
    echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
  fi
}

create() {
  if [[ -f "$CHROOTPATH64"/root/.arch-chroot ]]; then
    local mesg="Working directory $CHROOTPATH64 already exists."
    echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
  fi

  local pkgs=('base-devel')

  if [[ -n "$RUNDISTCC" ]]; then
    pkgs+=('distcc')
  fi

  [[ -d "$CCACHE_DIR" ]] && pkgs+=('ccache')
  [[ -f "$CUSTOM_PACMAN_CONF" ]] && insargs+=(-C "$CUSTOM_PACMAN_CONF")
  if [[ -f "$CUSTOM_MAKEPKG_CONF" ]]; then
    insargs+=(-M "$CUSTOM_MAKEPKG_CONF")
  else
    # there can be disconnects in variables between makepkg.conf provided by the pacman
    # package and the one provided by the devtools package so in order to maintain
    # consistent behavior of scripts like extra-x86_64-build and others listed on the wiki
    # under the "Convenience way" section (link below), we use the devtools 
    # makepkg-x86_64.conf rather than the one defined on the live system
    #
    # https://wiki.archlinux.org/title/DeveloperWiki:Building_in_a_clean_chroot#Convenience_way
    insargs+=(-M /usr/share/devtools/makepkg.conf.d/x86_64.conf)
  fi

  if ! mkarchroot "${insargs[@]}" "$CHROOTPATH64"/root "${pkgs[@]}"; then
    exit 1
  fi

  if [[ -n "$RUNDISTCC" ]]; then
    if [[ $DISTCCFAIL -ne 1 ]]; then
      sed -i -e '/#DISTCC_HOSTS/ s,#,,' \
        -i -e "/^DISTCC_HOSTS/ s|=\"\"|=\"$DISTCC_HOSTS\"|" \
        -i -e '/^BUILDENV/ s,!distcc,distcc,' "$CHROOTPATH64"/root/etc/makepkg.conf
    fi
  fi

  [[ -d "$CCACHE_DIR" ]] &&
    sed -i -e '/^BUILDENV/ s,!ccache,ccache,' "$CHROOTPATH64"/root/etc/makepkg.conf

  [[ -n "$PKGEXT" ]] &&
    sed -i -e "s/^PKGEXT.*/PKGEXT=\"$PKGEXT\"/" "$CHROOTPATH64"/root/etc/makepkg.conf

  if ! [[ -f "$CUSTOM_PACMAN_CONF" ]]; then
    # enable pacman color output in buildroot because I like it
    sed -i -e '/^#Color/ s,#,,' "$CHROOTPATH64"/root/etc/pacman.conf
  fi

  # if we are using an external repo and if it has a db, add it to pacman.conf if not do nothing
  if [[ $INTERNAL_REPO -ne 1 ]]; then
    if [[ -f "$REPO/$REPO_NAME.db.tar.gz" ]]; then
      if ! grep -q "$REPO_NAME" "$CHROOTPATH64/root/etc/pacman.conf"; then
        # add a local repo to buildroot
        sed -i "/\[core-testing\]/i \
          # Added by clean-chroot-manager\n[$REPO_NAME]\nSigLevel = Never\nServer = file://$REPO\n" \
                  "$CHROOTPATH64/root/etc/pacman.conf"
      fi
    fi
  else
    # make the empty dir for the repo in root's copy of the buildroot
    # note that we still have to modify pacman.conf to add a line for the repo
    # but only after it is populated with packages which is in the indexit function
    [[ -d "$REPO" ]] || mkdir "$REPO"
    chown "$USER" "$REPO"
  fi
}

addit() {
  if ! su -c "rsync -rlxDu --exclude '*.log' ./*.pkg.tar* $REPO/" "$USER" &>/dev/null; then
    local mesg="No packages found to add to local repo."
    echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
  fi
}

build() {
  args=('-u')
  [[ $NOCHECK -eq 1 ]] && postargs+=('--nocheck')
  [[ $CLEANIT -eq 1 ]] && args+=('-c')
  [[ -n "$RUNNAMCAP" ]] && args+=('-n')
  [[ -d "$CCACHE_DIR" ]] && args+=(-d "$CCACHE_DIR:/build/.ccache")
  [[ -d "$DISTCC_DIR" ]] && args+=(-d "$DISTCC_DIR:/build/.distcc")

  if [[ -f "$CUSTOM_MAKEPKG_CONF" ]]; then
    # makechrootpkg reads MAKEFLAGS and PACKAGER from the defined makepkg.conf
    # so honor those values here by not prefixing the call to makechrootpkg
    #echo makechrootpkg "${args[@]}" -r "$CHROOTPATH64" -- "${postargs[@]}"
    #exit
    if ! nice -n 19 makechrootpkg "${args[@]}" -r "$CHROOTPATH64" -- "${postargs[@]}"; then
      exit 1
    fi
  else
    # not using a custom makepkg.conf which means we're using the one on the live system so
    # we honor the values for MAKEFLAGS and PACKAGER in ~/.config/clean-chroot-manager.conf
    if ! PACKAGER="$PACKAGER" MAKEFLAGS=-j$THREADS nice -n 19 makechrootpkg "${args[@]}" -r "$CHROOTPATH64" -- "${postargs[@]}"; then
      exit 1
    fi
  fi

  # makepkg can can fail to build without throwing an error code so stop if
  # no .pkg.tar* is present in the dir
  [[ -n $(find . -maxdepth 1 -type f -name '*.pkg.tar*') ]] || exit 1
}

indexit() {
  local mesg="Adding all packages in current dir to buildroot repo..."
  echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"

  # external repos with db files are already setup when we made the buildroot
  # but for internal repos, if this is the first time a package has been built,
  # append the local repo to the buildroot's pacman.conf

  if ! grep -q "$REPO_NAME" "$CHROOTPATH64/root/etc/pacman.conf"; then
    # add a local repo to buildroot
    sed -i "/\[core-testing\]/i # Added by clean-chroot-manager\n[$REPO_NAME]\nSigLevel = Never\nServer = file://$REPO\n" "$CHROOTPATH64/root/etc/pacman.conf"

    # copy this pacman.conf back to the user copy if it exists... it may not if the user creates a
    # fresh buildroot and wants to populate it with pre-built pacakges
    if [[ -f "$CHROOTPATH64/$USER/etc/pacman.conf" ]]; then
      cp "$CHROOTPATH64/root/etc/pacman.conf" "$CHROOTPATH64/$USER/etc/pacman.conf"
    fi
  fi

  # it could be that the user is building for both i686 and x86_64
  # in which case we don't want to pollute the pure x86_64 repo
  # with i686 packages so only process 'x86_64' and 'any' types
  GLOBIGNORE="*namcap.log"
  for i in *.pkg.tar*; do
    su -c "cp $i $REPO" "$USER" || exit 1
    su -c "repo-add $REPO/$REPO_NAME.db.tar.gz $REPO/$i" "$USER" || exit 1

    ### do we really want this?
    # make sure that the buildroot package matches the live pacman cache package
    # to avoid a checksum error if the user builds the same package wo/ bumping the pkgver
    #[[ -f "/var/cache/pacman/pkg/$i" ]] && rm -f "/var/cache/pacman/pkg/$i"
  done
  unset GLOBIGNORE

  # The rm statement above can return 1 if the file to remove is not found,
  # causing the function to return a non-zero error code even if everything
  # went fine.  If we've made it to this point, the build was run
  # successfully, so return 0 instead
  return 0
}

update() {
  local mesg="Updating the buildroot..."
  echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
  arch-nspawn "$CHROOTPATH64"/root pacman -Syu --noconfirm
}

repocheck() {
  if [[ ! -f "$REPO/$REPO_NAME.db.tar.gz" ]]; then
    local mesg="Local repo is empty.  Build or manually populate packages first."
    echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
  fi
}

list() {
  local mesg="Listing out packages in buildroot repo..."
  echo -e "${GREEN}==>${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
  ls --color -lhF -I 'chroot*' "$REPO"
}

delete() {
  # remove all files from the repo including packages and databases
  rm -rf "${REPO:?}"/* 2>/dev/null
  rm -rf "${REPO:?}"/.* 2>/dev/null

  # modify pacman.conf so we don't error out due to missing databases
  if [[ -f "$CHROOTPATH64"/root/etc/pacman.conf ]]; then
    sed -i '/Added by clean/,+4d' "$CHROOTPATH64"/root/etc/pacman.conf
  fi
}

testing() {
  if [[ "$TESTING" = "Disabled" ]]; then
    # switch on testing
    local mesg="Enabling [*-testing] in buildroot..."
    echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
    sed -i -e '/^#\[core-testing\]/ s,#,,' \
      -i -e '/^\[core-testing\]/{$!N; s,#,,}' "$CHROOTPATH64"/root/etc/pacman.conf

    sed -i -e '/^#\[extra-testing\]/ s,#,,' \
      -i -e '/^\[extra-testing\]/{$!N; s,#,,}' "$CHROOTPATH64"/root/etc/pacman.conf

    local mesg="Forcing an update to use any affected packages..."
    echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
    arch-nspawn "$CHROOTPATH64"/root pacman -Syu --noconfirm
  elif [[ "$TESTING" = "Enabled" ]]; then
    # switch off testing
    local mesg="Disabling [*-testing] in buildroot..."
    echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"

    sed -i -e '/^\[core-testing\]/ s,\[,#\[,' \
      -i -e '/^#\[core-testing\]/{$!N; s,I,#I,}' "$CHROOTPATH64"/root/etc/pacman.conf

    sed -i -e '/^\[extra-testing\]/ s,\[,#\[,' \
      -i -e '/^#\[extra-testing\]/{$!N; s,I,#I,}' "$CHROOTPATH64"/root/etc/pacman.conf

    local mesg="Downgrading affected packages if any..."
    echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
    arch-nspawn "$CHROOTPATH64"/root pacman -Syuu --noconfirm
  fi
}

preview() {
  echo -e "${BOLD}$PKG v$VERS${ALL_OFF}"
  echo
  if [[ -f "$CHROOTPATH64"/root/.arch-chroot ]]; then
    HERE=1
    PRESENT="${BOLD}($(du -sh "$CHROOTPATH64" 2>/dev/null|awk '{ print $1 }'))${ALL_OFF}"
  else
    PRESENT="${BOLD}${RED}(None present)${ALL_OFF}"
  fi

  echo -en "${BOLD} buildroot path:"
  echo -e "$(tput cr)$(tput cuf 18)${BLUE}$CHROOTPATH64/${ALL_OFF}${BOLD} $PRESENT${ALL_OFF}"

  if [[ -n "$CCACHE_DIR" ]]; then
    CCSIZE=$(du -sh "$CCACHE_DIR" 2>/dev/null|awk '{ print $1 }')
    # if null contents write out a pretty message
    [[ "$CCSIZE" = "0" ]] && CCSIZE="${BOLD}${RED}(Empty cache)${ALL_OFF}" || CCSIZE="${BOLD}($CCSIZE)${ALL_OFF}"
    echo -en "${BOLD} ccache path:"
    echo -e "$(tput cr)$(tput cuf 18)${BLUE}$CCACHE_DIR/${ALL_OFF} $CCSIZE"
  fi

  if [[ -f "$CUSTOM_PACMAN_CONF" ]]; then
    echo -en "${BOLD} custom config:"
    echo -e "$(tput cr)$(tput cuf 18)$CUSTOM_PACMAN_CONF${ALL_OFF}${BOLD}${ALL_OFF}"
  fi

  if [[ -f "$CUSTOM_MAKEPKG_CONF" ]]; then
    echo -en "${BOLD} custom config:"
    echo -e "$(tput cr)$(tput cuf 18)$CUSTOM_MAKEPKG_CONF${ALL_OFF}${BOLD}${ALL_OFF}"
    # use threads value from the custom config
    BR_THREADS=$(grep MAKEFLAGS= "$CUSTOM_MAKEPKG_CONF")
    THREADS="${BR_THREADS//[^0-9]/}"
  fi

  if [[ -d "$REPO" ]]; then
    if ! find "$REPO" -maxdepth 0 -type d -empty |grep -q .; then
      REPOSIZE="${BOLD}$(du -sh "$REPO" 2>/dev/null|awk '{ print $1 }')${ALL_OFF}"
    else
      REPOSIZE="${BOLD}${RED}(Empty repo)${ALL_OFF}"
    fi
  else
    REPOSIZE="${BOLD}${RED}(Empty repo)${ALL_OFF}"
  fi
  echo
  echo -en "${BOLD} repo path:"
  echo -e "$(tput cr)$(tput cuf 18)${BLUE}$REPO/${ALL_OFF}${BOLD}${ALL_OFF} $REPOSIZE"
  echo -en "${BOLD} repo name:"
  echo -e "$(tput cr)$(tput cuf 18)$REPO_NAME${ALL_OFF}${BOLD}${ALL_OFF}"

  if [[ HERE -eq 1 ]]; then
    echo
    echo -en "${BOLD} buildroot threads:"
    echo -e "$(tput cr)$(tput cuf 21)${BOLD}$THREADS${ALL_OFF}"

    if [[ $(grep -c '^#\[core-testing]' "$CHROOTPATH64"/root/etc/pacman.conf) -eq 0 ]]; then
      TESTING_C="${BOLD}${GREEN}[*-testing]${ALL_OFF}"
    else
      TESTING_C="${RED}[*-testing]${ALL_OFF}${BOLD}"
    fi

    if [[ $(grep '^BUILDENV' "$CHROOTPATH64"/root/etc/makepkg.conf | grep -c '!distcc') -eq 0 ]]; then
      DISTCC_C="${BOLD}${GREEN}distcc${ALL_OFF}"
    else
      DISTCC_C="${RED}distcc${ALL_OFF}${BOLD}"
    fi

    if [[ $(grep '^BUILDENV' "$CHROOTPATH64"/root/etc/makepkg.conf | grep -c '!ccache') -eq 0 ]]; then
      CCACHE_C="${BOLD}${GREEN}ccache${ALL_OFF}"
    else
      CCACHE_C="${RED}ccache${ALL_OFF}${BOLD}"
    fi

    echo -en "${BOLD} buildroot options:"
    echo -e "$(tput cr)$(tput cuf 21)${BOLD}$TESTING_C  $DISTCC_C  $CCACHE_C${ALL_OFF}"

    if pidof -q -x makechrootpkg; then
      etime=$( ps --no-headers -o %t "$(pidof -x sudo ccm | awk '{ print $(NF) }')" )
      echo;  echo -en "${BOLD} building, elasped:"
      echo -e "$(tput cr)$(tput cuf 21)${BOLD}${etime/      /}${ALL_OFF}"
    fi
  fi
}

##
#  Copied from https://git.archlinux.org/devtools.git/tree/lib/archroot.sh
##

##
#  Returns if the $path is a the root of a btrfs subvolume (including
#           the top-level subvolume).
#
#  usage  : is_subvolume( $path )
#  return : true if it is, false if not
##
is_subvolume() {
  [[ -e "$1" && "$(stat -f -c %T "$1")" == btrfs && "$(stat -c %i "$1")" == 256 ]]
}

##
#  Find all btrfs subvolumes under and including $path and delete them.
#
#  usage  : subvolume_delete_recursive( $path )
#  return : 0 if it was successful, 1 if not.
##
subvolume_delete_recursive() {
  local subvol
  is_subvolume "$1" || return 0
  while IFS= read -d $'\0' -r subvol; do
    if ! subvolume_delete_recursive "$subvol"; then
      return 1
    fi
  done < <(find "$1" -mindepth 1 -xdev -depth -inum 256 -print0)
  if ! btrfs subvolume delete "$1" &>/dev/null; then
    error "Unable to delete subvolume %s" "$subvol"
    return 1
  fi
  return 0
}

nuke() {
  if [[ $(stat -f -c %T "$CHROOTPATH64") == btrfs ]]; then
    for i in "$CHROOTPATH64"/*; do
      if [ -d "$i" ]; then
        subvolume_delete_recursive "$i" || return 255
      else
        rm -f "$i"
      fi
    done
  else
    rm -rf "${CHROOTPATH64:?}"/*
  fi
}

purgecache() {
  local mesg="Purging ccache..."
  echo -e "${GREEN}==>${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
  if [[ $(stat -f -c %T "$CCACHE_DIR") == btrfs ]]; then
    for i in "$CCACHE_DIR"/*; do
      if [ -d "$i" ]; then
        subvolume_delete_recursive "$i" || return 255
      else
        rm -f "$i"
      fi
    done
  else
    rm -rf "${CCACHE_DIR:?}"/*
  fi
}

distcc_check() {
  # this is a catch-all function to check for a running distcc and to
  # override the THREADS value due to https://bugs.archlinux.org/task/64349
  # which to is not fixed even though it is closed

  # if the buildroot is already created, see if distcc is enabled and
  # simply set RUNDISTCC which may or may not be set in the config file
  # if the user created the buildroot with the 'cd' switch

  if [[ -f "$CHROOTPATH64/root/etc/makepkg.conf" ]]; then
    if grep -q -i '^BUILDENV=(distcc' "$CHROOTPATH64/root/etc/makepkg.conf"; then
      # a buildroot is present with distcc enabled
      RUNDISTCC=y
    fi
  fi

  # RUNDISTCC can also be forced via the 'cd' swtich as well as set in the config
  if [[ -n "$RUNDISTCC" ]]; then
    # fail if distcc_threads aren't defined
    if [[ -z "$DISTCC_THREADS" ]]; then
      local mesg="Define DISTCC_THREADS in $CFGFILE to build with distcc."
      echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
    fi
    # need to prefix the call to makechrootpkg with threads value
    # https://bugs.archlinux.org/task/64349
    THREADS=$DISTCC_THREADS
  fi
}

case "$1" in
  a)
    check_config && addit && indexit
    ;;
  c)
    check_config && check_active && distcc_check && create
    ;;
  cd)
    # force running with distcc to override the config file setting
    check_config && check_active && distcc_check
    RUNDISTCC=y
    create
    ;;
  pc)
    check_config && purgecache
    ;;
  t)
    check_config && check_active && check_buildroot && testing
    # no need to call update since testing function handles this
    ;;
  d)
    check_config && repocheck
    mesg="Deleting all packages and index in buildroot repo..."
    echo -e "${GREEN}==>${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
    delete
    ;;
  l)
    check_config && repocheck && list
    ;;
  n)
    mesg="Deleting the entire buildroot..."
    echo -e "${GREEN}==>${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
    check_config && check_active && nuke
    ;;
  N)
    mesg="Deleting the entire buildroot and external repo..."
    echo -e "${GREEN}==>${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
    check_config && check_active && delete && nuke
    ;;
  p)
    check_config && distcc_check && preview
    ;;
  R)
    check_config
    if [[ ! -f "$CHROOTPATH64"/root/.arch-chroot ]]; then
      mesg="No buildroot has been created/nothing to repackage."
      echo -e "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"; exit 1
    fi

    postargs+=('-R')
    mesg="Attempting to repackage..."
    echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
    # flag to NOT add a '-c' to the args array
    CLEANIT=0

    check_active && build && indexit
    ;;
  s)
    check_config && check_active && distcc_check
    if [[ ! -f "$CHROOTPATH64"/root/.arch-chroot ]]; then
      mesg="No buildroot has been created so making one now..."
      echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
      create
    fi

    mesg="Attempting to build package..."
    echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"

    # flag to add '-c' to the args array
    CLEANIT=1
    build && indexit
    ;;
  S)
    check_config && check_active && distcc_check
    if [[ ! -f "$CHROOTPATH64"/root/.arch-chroot ]]; then
      mesg="No buildroot has been created so making one now..."
      echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"
      create
    fi

    mesg="Attempting to build package..."
    echo -e "${YELLOW}---->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}"

    # flag to NOT add a '-c' to the args array
    CLEANIT=0
    build && indexit
    ;;
  u)
    check_config && check_active && check_buildroot && update
    ;;
  *)
    echo -e "${BOLD}$PKG v$VERS${ALL_OFF}"
    echo
    echo -e "${BOLD} Usage: ${RED}$0${ALL_OFF}${BOLD} ${ALL_OFF}${BLUE}[option]${ALL_OFF}"
    echo
    echo -e "${BOLD} --- SETUP AND BREAKDOWN  ---"
    echo -e "${BOLD}   c) Create the buildroot${ALL_OFF}"
    echo -e "${BOLD}  cd) Create the buildroot with distcc${ALL_OFF}"
    echo -e "${BOLD}   N) Nuke the buildroot and external repo (if defined)${ALL_OFF}"
    echo -e "${BOLD}   n) Nuke the buildroot${ALL_OFF}"
    echo -e "${BOLD}   t) Toggle [*-testing] on/off${ALL_OFF}"
    echo
    if [[ -n "$CCACHE_DIR" ]]; then
      echo -e "${BOLD} Target: ${BLUE}$CCACHE_DIR${ALL_OFF}"
      echo -e "${BOLD}  pc) Purge the ccache${ALL_OFF}"
      echo
    fi
    echo -e "${BOLD} --- BUILDING ---${ALL_OFF}"
    echo -e "${BOLD}   R) Repackage (passes '-R' to default)${ALL_OFF}"
    echo -e "${BOLD}   S) Run makepkg but do not clean first${ALL_OFF}"
    echo -e "${BOLD}   s) Run makepkg (default)${ALL_OFF}"
    echo
    echo -e "${BOLD} --- LOCAL REPO ---${ALL_OFF}"
    echo -e "${BOLD}   a) Add packages in current dir to the local repo${ALL_OFF}"
    echo -e "${BOLD}   d) Delete all packages in the local repo${ALL_OFF}"
    echo -e "${BOLD}   l) List packages in local repo${ALL_OFF}"
    echo
    echo -e "${BOLD} --- MISCELLANEOUS ---"
    echo -e "${BOLD}   p) Preview settings${ALL_OFF}"
    echo -e "${BOLD}   u) Update clean buildroot${ALL_OFF}"
    ;;
esac

# vim:set ts=2 sw=2 et:
