#!/bin/bash
# return bx_type based on RAM on system
# current types:
# 1   => RAM < 500MB
# 2   => RAM: 500MB   - 1GB
# 3   => RAM: 1GB     - 1,5GB
# 4   => RAM: 1,5GB   - 2GB
# 5   => RAM: 2GB     - 3GB
# 6   => RAM: 3GB     - 4GB
# 7   => RAM: 4GB     - 5GB
# 8   => RAM: 5GB     - 6GB
# 9   => RAM: 6GB     - 8GB
# 10  => RAM: >= 8GB

DEBUG=0
TMP_DIR=/tmp
[[ -d /dev/shm/ ]] && TMP_DIR=/dev/shm
LOG_FILE=$TMP_DIR/bx_vat_$$.log

export LANG=en_EN.UTF-8

debug(){
  mess=$1

  [[ $DEBUG -gt 0 ]] && echo "$(date +%s) $mess" >> $LOG_FILE
}

get_memory() {
  
  is_vps=1
  memory=$(free | awk '/Mem/{print $2}')

  # openvz installation
  if [[ -f /proc/user_beancounters ]]; then
    # > 500MB
    # problem with: Unable to fork: Cannot allocate memory
    if [[ -z "$memory" ]]; then
      # Memory allocation guarantee.
      mem4kblock=$(cat /proc/user_beancounters  | awk '/vmguarpages/{print $4}')

      # The current amount of allocated memory space is accounted into privvmpages parameter
      mem4kblock2=$(cat /proc/user_beancounters | awk '/privvmpages/{print $4}')
    
      memory=$(echo "${mem4kblock2} * 4"|bc)
      [[ $mem4kblock2 -gt $mem4kblock ]] && memory=$(echo "${mem4kblock} * 4"|bc)

    fi
  else
    is_vps=0
  fi

  echo $memory
}

get_bx_version() {
  release_file=/etc/redhat-release
  if [[ ! -f $release_file ]]; then
    if [[ -f /etc/centos-release ]]; then
      release_file=/etc/centos-release
    else
      echo "{\"changed\":false,\"failed\":true,\"msg\":\"not found rpm based OS\"}"
      exit 1
    fi
  fi

  debug "Found RPM system, continue"
  
  package_name=bitrix-env
  package_data=$TMP_DIR/${package_name}_$(date +%s)_$$.pkginfo
  rpm -qi "$package_name" >$package_data 2>$package_data
  
  # if package not installed
  if [[ $? -gt 0 ]]; then
    # test if 4 version
    package_name=bitrix-env4
    package_data=$TMP_DIR/${package_name}_$(date +%s)_$$.pkginfo
    rpm -qi "$package_name" >$package_data 2>$package_data

    if [[ $? -gt 0 ]]; then
      PACKAGE=0
      debug "rpm -qi $package_name return error"
    else
      bitrix_env_version=$(egrep -o '^Version\s*:\s*[0-9\.]+' $package_data | \
       awk -F':' '{print $2}' | sed -e 's/\s\+//g')
      
      # test version value
      if [[ -z "$bitrix_env_version" ]]; then
        echo "{\"changed\":false,\"failed\":true,\"msg\":\"not found version for package\"}"
        debug "not found version for $package_name"
    
        rm -f $package_data
        exit 1
      fi
      # create package info
      debug "found pakache info: bitrix_env_version=$bitrix_env_version bitrix_env_release=$bitrix_env_release"
      PACKAGE="4."$bitrix_env_version
    fi

  # rpm not return error, get version and release number
  else
    bitrix_env_version=$(egrep -o '^Version\s*:\s*[0-9\.]+' $package_data | \
     awk -F':' '{print $2}' | sed -e 's/\s\+//g')
    bitrix_env_release=$(egrep -o '^Release\s*:\s*[0-9]+' $package_data | \
     awk -F':' '{print $2}' | sed -e 's/\s\+//g')
    
    # test version value
    if [[ -z "$bitrix_env_version" ]]; then
      echo "{\"changed\":false,\"failed\":true,\"msg\":\"not found version for package\"}"
      debug "not found version for $package_name"
    
      rm -f $package_data
      exit 1
    fi
    # test release value
    if [[ -z "$bitrix_env_release" ]]; then
      echo "{\"changed\":false,\"failed\":true,\"msg\":\"not found release for package\"}"
      debug "not found release for $package_name"    
 
      rm -f $package_data
      exit 1
    fi
    # create package info
    debug "found pakache info: bitrix_env_version=$bitrix_env_version bitrix_env_release=$bitrix_env_release"
    PACKAGE=$bitrix_env_version"-"$bitrix_env_release
  fi

  rm -f $package_data
}

get_bx_user_password(){
  bx_user=bitrix

  chage_data=$TMP_DIR/${bx_user}_$(date +%s)_$$.change
  # test if user exists
  user_found=$(grep -c "^$bx_user:" /etc/passwd)
  user_id=$(grep "^$bx_user:" /etc/passwd | awk -F':' '{print $3}')
  if [[ $user_found -gt 0 ]]; then
    debug "Found user $bx_user in the system"

    chage -l $bx_user > $chage_data 2>&1

    if [[ $? -gt 0 ]]; then
      echo "{\"changed\":false,\"failed\":true,\"msg\":\"cmd return error\"}"
      debug "\"chage -l $bx_user return error\""
      rm -f $chage_data
      exit 1
    fi

    Last_password_change=$( awk -F':' '/Last password change/{print $2}' $chage_data| sed 's/^\s\+//;s/\s\+$//;')
    Password_expires=$(     awk -F':' '/Password expires/{print $2}'     $chage_data| sed 's/^\s\+//;s/\s\+$//;')
    Password_inactive=$(    awk -F':' '/Password inactive/{print $2}'    $chage_data| sed 's/^\s\+//;s/\s\+$//;')
  else
    Last_password_change=0
    Password_expires=0
    Password_inactive=0
  fi
  
  rm -f $chage_data
}
get_bx_root_password(){
  root_bx_user=root

  chage_data=$TMP_DIR/${root_bx_user}_$(date +%s)_$$.change
  # test if user exists
  root_user_found=$(grep -c "^$root_bx_user:" /etc/passwd)
  root_user_id=$(grep "^$root_bx_user:" /etc/passwd | awk -F':' '{print $3}')
  if [[ $root_user_found -gt 0 ]]; then
    debug "Found user $root_bx_user in the system"

    chage -l $root_bx_user > $chage_data 2>&1

    if [[ $? -gt 0 ]]; then
      echo "{\"changed\":false,\"failed\":true,\"msg\":\"cmd return error\"}"
      debug "\"chage -l $root_bx_user return error\""
      rm -f $chage_data
      exit 1
    fi

    root_Last_password_change=$( awk -F':' '/Last password change/{print $2}' $chage_data| sed 's/^\s\+//;s/\s\+$//;')
    root_Password_expires=$(     awk -F':' '/Password expires/{print $2}'     $chage_data| sed 's/^\s\+//;s/\s\+$//;')
    root_Password_inactive=$(    awk -F':' '/Password inactive/{print $2}'    $chage_data| sed 's/^\s\+//;s/\s\+$//;')
  else
    root_Last_password_change=0
    root_Password_expires=0
    root_Password_inactive=0
  fi
  
  rm -f $chage_data
}


get_bx_network(){
  ip_link_list=$(ip link show | egrep -o '^[0-9]+:\s+\S+' | \
    awk '{print $2}' | sed -e 's/://g;s/\s\+//g;' | grep -v '^lo$')
  
  INT_INFO=''
  # current throughput
  for int in $ip_link_list; do
    ethtool_info=$(ethtool $int | egrep -o '(Speed|Link detected):\s+\S+')
    speed=$(echo "$ethtool_info" | awk -F':' '/Speed/{print $2}' | sed -e 's/://g;s/\s\+//g;')
    link=$( echo "$ethtool_info" | awk -F':' '/Link/{print $2}'  | sed -e 's/://g;s/\s\+//g;')
    
    if [[ $(echo "$link" | grep -wc 'yes') -gt 0 ]]; then
      INT_INFO=$INT_INFO"\"link_$int\":\"yes\",\"speed_$int\":\"$speed\","
      inet_addr=$(ip addr show $int | egrep -o "inet\s+\S+" | sed -e 's/^inet\s\+//;s:/[0-9]\+$::;')
      INT_INFO=$INT_INFO"\"addr_$int\":\"$inet_addr\","
    else
      INT_INFO=$INT_INFO"\"link_$int\":\"no\",\"speed_$int\":\"0\",\"addr_$int\":\"none\","
    fi
  done

}
# return  number
# outdated
get_bx_systemtype(){
  system_type=1
  system_memory=$(get_memory) # KB

  [[ ( $system_memory -gt 500000 )  && ( $system_memory -lt 1000000 ) ]] && system_type=2
  [[ ( $system_memory -gt 1000000 ) && ( $system_memory -lt 1500000 ) ]] && system_type=3
  [[ ( $system_memory -gt 1500000 ) && ( $system_memory -lt 2000000 ) ]] && system_type=4
  [[ ( $system_memory -gt 2000000 ) && ( $system_memory -lt 3000000 ) ]] && system_type=5
  [[ ( $system_memory -gt 3000000 ) && ( $system_memory -lt 4000000 ) ]] && system_type=6
  [[ ( $system_memory -gt 4000000 ) && ( $system_memory -lt 5000000 ) ]] && system_type=7
  [[ ( $system_memory -gt 5000000 ) && ( $system_memory -lt 6000000 ) ]] && system_type=8
  [[ ( $system_memory -gt 6000000 ) && ( $system_memory -lt 8000000 ) ]] && system_type=9
  [[ $system_memory -gt 8000000 ]] && system_type=10

}

## rpm packages info
get_bx_packages(){
  rpm_bin=$(which rpm 2>/dev/null)
  if [[ -n "$rpm_bin" ]]; then
    mysql_version=$($rpm_bin -qa --queryformat '%{name} %{version} \n' mysql | awk '{print $2}')
    php_version=$($rpm_bin -qa --queryformat '%{name} %{version} \n' php | awk '{print $2}')
  fi

  [[ -z $mysql_version ]] && mysql_version='not_installed'
  [[ -z $php_version ]] && php_version='not_installed'
  [[ -z $rpm_bin ]] && rpm_bin='not_installed'
}
# return max memory of this type
# new
get_bx_systemtype_mem(){
  memory_limits="256:512:1024:1536:2048:3072:4096:5120:6144:7168:8192:9216:10240:11264:12288:13312:14336:15360:16384:65536"
  min_mb=0

  memory=$(get_memory)
  memory_mb=$((${memory}/1024))
  system_type_by_memory=256

  os_arch=$(uname -p)
  if [[ $(echo "$os_arch" | grep -c '\(i686\|i386\)') -gt 0 ]]; then
    [[ $memory_mb -gt 4096 ]] && memory_mb=4096
  fi

  for max_mb in $(echo $memory_limits| sed -e 's/:/ /g;' ); do
    if [[ $memory_mb -gt $min_mb && $memory_mb -le $max_mb ]]; then
      system_type_by_memory=$max_mb
    fi
    min_mb=$max_mb
  done
}

debug "start get_bx_version"
get_bx_version

debug "start get_bx_user_password"
get_bx_user_password

debug "start get_bx_root_password"
get_bx_root_password

debug "start get_bx_network"
get_bx_network

debug "start get_bx_systemtype"
get_bx_systemtype

debug "start get_bx_systemtype_mem"
get_bx_systemtype_mem

debug "start get_bx_packages"
get_bx_packages

ANSIBLE_OUTPUT='{"ansible_facts":{'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"bx_system_type":"'$system_type'",'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"bx_memsystem_type":"'$system_type_by_memory'",'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"bx_memory":"'$memory'",'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"bx_version":"'$PACKAGE'",'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"bx_base_version":"'$(echo "$PACKAGE" | awk -F'.' '{print $1}')'",'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT$INT_INFO
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"bx_bitrix_uid":"'$user_id'",'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"rpm_bin":"'$rpm_bin'",'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"mysql_version":"'$mysql_version'",'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"php_version":"'$php_version'",'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"bx_root_last_password_change":"'$root_Last_password_change'",'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'"bx_last_password_change":"'$Last_password_change'"'
ANSIBLE_OUTPUT=$ANSIBLE_OUTPUT'}}'

echo -n $ANSIBLE_OUTPUT
exit 0
