#!/bin/bash
# phpmoves.sh - Generate a list of the cPanel users and their current PHP versions
# Copyright 2023 World Host Group.
# Tsvetan Gerov <tsvetan@worldhost.group>
# Version 0.2

if [ ! -x /usr/bin/selectorctl ]; then
  echo "Error: This server is not using CloudLinux's PHP selector"
  exit 1
fi

case $1 in
  generate)
    nativeVersion=$(selectorctl --show-native-version)
    serverHostname=$(hostname -f)
    CPUSERS=$(whmapi1   listaccts | grep user | awk '{print$2}')
    OUTPUT=${serverHostname}.txt
    truncate -s 0 $OUTPUT
    for CPUSER in $CPUSERS; do
      if getent passwd $CPUSER > /dev/null 2>&1; then
        PHPVER=$(selectorctl --user-current --user=${CPUSER} | awk '{print$1}')
        if [ $PHPVER == "native" ]; then
          PHPVER=$nativeVersion
        fi
        echo "$CPUSER : $PHPVER" | tee -a $OUTPUT
      fi
    done
    echo "Transfer $OUTPUT file to the new server and execute ./$(basename $0) load $OUTPUT"
  ;;

  load)
    FILE=$2
    echo "Loading $FILE..."
    CPUSERS=$(cat $FILE | awk '{print$1}')
    for CPUSER in $CPUSERS; do
      if getent passwd $CPUSER > /dev/null 2>&1; then
        PHPVER=$(grep -w ^${CPUSER} $FILE | awk '{print$3}')
        echo "=> $CPUSER: Settings PHP version to $PHPVER"
        selectorctl --set-user-current=$PHPVER --user=$CPUSER
      else
        echo "--> User $CPUSER does not exists on this server."
      fi
    done
  ;;

  *)
    echo "Usage: $(basename $0) generate|load"
    echo "generate - generate a list with users and their curent php versions"
    echo "load <filename> - set a users php versions from a generated list"
  ;;
esac

