export HISTTIMEFORMAT="%Y-%m-%d %T "
export OCTO_HISTORY_FILE="/root/.octo_history"

NEW="Zukunftsmajo hat Bock -> TODO\n" 

##################################
# Support helper-script by mr/md #
##################################

# regular colors
RST="\033[0;0m"    # RESET colors
K="\033[0;30m"    # black
R="\033[0;31m"    # red
G="\033[0;32m"    # green
Y="\033[0;33m"    # yellow
B="\033[0;34m"    # blue
M="\033[0;35m"    # magenta
C="\033[0;36m"    # cyan
W="\033[0;37m"    # white

# bold colors (same in bold)
EMK="\033[1;30m"  # black
EMR="\033[1;31m"  # red
EMG="\033[1;32m"  # green
EMY="\033[1;33m"  # yellow
EMB="\033[1;34m"  # blue
EMM="\033[1;35m"  # magenta
EMC="\033[1;36m"  # cyan
EMW="\033[1;37m"  # white

ST=80

##################################
#        CUSTOM FUNCTIONS        #
##################################


#################################
# Show colored title (title "<text>" "<fillerchar>")
title()
{
  SPACE=$((${#1}+2))

  printf "${C}"
  for (( i = 0; i < $ST; i++ )); do
    if [[ $i -eq $(($ST / 2 - $SPACE / 2)) ]]; then
      printf " $1 "
      i=$(($i+$SPACE))
    else
      printf "$2"
    fi
  done
  printf "${W}\n"
}


#################################
# Prints ethtool for interface <ethX>
detect_link()
{
    local dev=$1
    if [[ "$dev" != "wg"* ]]
    then
        if [[ $(ethtool $1 | grep Link\ detected) == *"yes" ]]
        then
            printf  "${EMG}YES"
        else
            printf  "${EMR}NO"
        fi
    else
        if [[ ! -z $(wg | grep $dev) ]]
        then
            printf  "${EMG}YES"
        else
            printf  "${EMG}NO"
        fi 
    fi
}

#################################
# Prints ip for interface <ethX>
get_ip()
{
  IP=$(ifconfig $1  2>&1| grep inet | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | head -1)
  if [[ -z ${IP} ]]; then
    printf "${EMR}none\t"
  else
    printf $IP; echo
  fi
}

#################################
# Print first helpful information
oginfo()
{

    RAMINFO=$(free -m |  free -m | grep Mem | awk '{print $3 " / " $2}')
    WBVAR="${EMR}FAILED"
    CNT_USERS=0
    UPTIME=$(uptime | sed 's/,/ /g' | awk '{print $3,$4}')

    test -f /data/.maintenance/migration.done \
        && LAST_UPDATED="$(cat /data/.maintenance/migration.done | grep Date | sed 's/Date:\s*//')"

    title "OctoGate 4 INFO" "#"
    echo -e "${W}CUSTOM aliases etc. type ${R}mrhelp${W} to get a detailed list"
    echo -e "${W}or use ${R}oginfo${W} to view these infos again"


    local IFS_old=$IFS
    IFS=' ' 

    title "Main Status" "-"
    echo ""
    local status=$(oc main_status)
    echo $status | head -n 3 | tail -n 2 | sed 's/:/:\t/g' | sed 's/,/\t/g'
    echo $status | tail -n 3 | head -n 2 | sed 's/:/:\t/2'
    echo ""
    IFS='' 
    echo $status | tail -n 1
    echo ""


    title "WIFI Info" "-"

    local ap_status=$(oc ap)

    echo -e "${W}APs ONLINE:\t\t\t ${EMG}`echo $ap_status | grep ONLINE | wc -l`"
    echo -e "${W}APs OFFLINE:\t\t\t ${EMR}$((`echo $ap_status | grep -E 'OFFLINE|BOOTLOADER|OS_INIT' | wc -l`))"

    IFS=$IFS_old

    if [[ ! -z $result ]]
    then
            echo "Caching Server Active"
    fi


    if [ "$OCTO_AD_PASSWORD" != "" ]; then
         title "AD Info" "-"
         echo -e "${EMC}AD Server: \t\t\t ${EMG}${OCTO_AD_SERVER} ( ${OCTO_AD_SERVER_IP} )"
         printf "%s %17s : %5s\n"  "${OCTO_AD_DOMAIN}" "${OCTO_AD_ADMINISTRATOR}" "${OCTO_AD_PASSWORD}" # old values 36s 10s
         echo -e "${W}Users imported from AD: \t ${EMG}${CNT_USERS}"
         echo -e "${W}wbinfo -t\t\t\t ${WBVAR}"
    fi

    title "IP Info" "-"

    for order in int wan tun wg
    do
        list=$(ip --oneline link |  cut -d : -f 2 | grep $order | sort -d)
        for dev in $list
        do 
            echo -e "${W}IP ${EMM}$dev\t${EMG}$(get_ip $dev)${W}\t\t INT\tLink:\t$(detect_link $dev)"
        done
    done


    echo -e "${W}Link WebGUI:${W}\t\t\t https://$HOSTNAME-vpn.ozone.octogate.de"

    title "SYS Info" "-"
    df -h | egrep sda6\|hda6 | awk -v red="$(tput setaf 1)" -v green="$(tput setaf 2)"\
        -v yellow="$(tput setaf 3)" -v reset="$(tput sgr0)" \
        '{ if ($5>90) color=red; else if ($5>80) color=yellow; else color=green
        printf "%s%s%s on %s%s\t\t %s%s\n",color, $1, reset, color, $6, $5, reset }'
    if [[ $(grep "sda6.*\sro[\s,]" /proc/mounts) ]]; then
        echo -e "${EMR}### WARNING: SDA6 IS READONLY!!! ###"
    fi
    FILE=/etc/octo/confdeploy.txt
    if test -f "$FILE"; then
     cat $FILE | tr '\n' ' '| grep -i lmz &>/dev/null;
     if [ $? == "0" ]; then
      depv=$(cat $FILE | tr '\n' ' '| grep -i lmz| awk '{print $2}')
      echo -e "Confd-Ver.:\t\t\t $depv"
     fi;
    fi

    if [ "$LAST_UPDATED" != "" ]; then
      echo -e "${W}Last Update:\t\t\t ${W}${LAST_UPDATED}"
    fi
    echo -e "${W}Uptime:\t\t\t\t ${W}${UPTIME}"
    echo -e "${W}RAM:\t\t\t\t ${W}${RAMINFO} MB used"


    title "SSH connections" "-"
    a=$(ps -aux | grep -i tmp | grep -i SSH_USR | cut -d "'" -f 2); echo -en "Angemeldete Socto-User:(" $a "),"
    echo -en " gesamte Anzahl SSH-User: " 
    Anz_Us=$(ps -aux | grep -i sshd: | grep -v grep | wc -l)
    echo $Anz_Us

    ls /etc/octo/opf.d/08_icmp &>/dev/null || ls /data/havp_fix/havpwhite.txt &>/dev/null;
    if [ $? == "0" ]; then
        title "inserted rules" "-"
        echo -ne "${R}"
    ls /etc/octo/opf.d/08_icmp &>/dev/null;
     if [ $? == "0" ]; then
        echo -e "${W} nextcloud_fix ${EMG}\t\t\t active"

     fi;
     ls /data/havp_fix/havpwhite.txt &>/dev/null;
     if [ $? == "0" ]; then
        echo -e "${W} havp_fix ${EMG}\t\t\t active"

     fi;
    fi;

    title "END" "#"

    echo -e ">>> Newest feature: ${NEW}"
}

#################################
# US 03 random joke
octo_joke()
{
	curl -s --insecure https://www.zufallswitz.de/ | grep "bookmark" | grep href\=.**\<\/a | grep -o summary\"\>.**\<\/div\> | cut -d ">" -f2 | cut -d "<" -f1 | sed -e 's/\&\#....\;//'g | sed "s/.\{160\}/&\\n/g"
}

################################
# US 03 random joke20
octo_joke20()
{
  clear; curl -L -s --insecure https://www.witze-fun.de/witze/zufallswitz/ | grep -o '<p>'.* | grep -v rating | grep -o ".*</p>" | sed 's/&quot;//g' | sed 's/&uuml;/ü/g' | sed 's/&szlig;/ß/g' | sed 's/&ouml;/ö/g' | sed 's/&auml;/ä/g' | sed 's/<p>//g' | sed 's/<\/p>//g'
}

#################################
# builds base-DN from OCTO-vars
get_bind_dn()
{
    echo $OCTO_AD_DOMAIN | tr '.' '\0' | xargs -0 printf "dc=%s," | sed -E 's/,$//'
}

#################################
# builds admin-DN from OCTO-vars
get_admin_dn()
{
    local BINDDN=$(get_bind_dn)
    echo "CN=${OCTO_AD_ADMINISTRATOR},CN=Users,${BINDDN}"
}

#################################
# returns DN of given object
get_dn_of()
{
    local BINDDN=$(get_bind_dn)

    local LDAP_OPT="-x -LLL"
    LDAP_OPT="${LDAP_OPT} -h ${OCTO_AD_SERVER}"
    LDAP_OPT="${LDAP_OPT} -D $(get_admin_dn)"
    LDAP_OPT="${LDAP_OPT} -w ${OCTO_AD_PASSWORD}"
    LDAP_OPT="${LDAP_OPT} -b ${BINDDN}"

    local FOUND_DN=$(ldapsearch ${LDAP_OPT} ${1} dn | grep ^dn | cut -d " " -f 2)

    echo "${FOUND_DN}"
}

#################################
# Confirm-Loop
confirm()
{
    title "$1" "-"

    while true
    do
        read -r -p "Are You Sure? [Y/n] " input

        case $input in
            [yY][eE][sS]|[yY])
                return 0
                ;;
            [nN][oO]|[nN])
                return 1
                ;;
            *)
                echo "Invalid input..."
                ;;
        esac
    done
}

#################################
# echo ldap-options for ldapmodify / ldapsearch queries
get_ldap_opts()
{
    local BINDDN=$(get_bind_dn)

    local LDAP_OPT="-h ${OCTO_AD_SERVER_IP}"
    LDAP_OPT="${LDAP_OPT} -b ${BINDDN}"

    ########################################

    if [[ -z $2 ]]
    then
        LDAP_OPT="${LDAP_OPT} -D $(get_admin_dn)"
        LDAP_OPT="${LDAP_OPT} -w ${OCTO_AD_PASSWORD}"
    else
        local USER_DN=$(get_dn_of "sAMAccountname=$1")
        LDAP_OPT="${LDAP_OPT} -D ${USER_DN}"
        LDAP_OPT="${LDAP_OPT} -w $2"
    fi

    ########################################

    echo "${LDAP_OPT}"
}

#################################
# check_ldap_auth [user] [pw] - checks if ldap-bind is possible
check_ldap_auth()
{
    local LDAP_OPT=$(get_ldap_opts "$1" "$2")
    title "testing ldap-auth" "-"

    set -x
    ldapsearch ${LDAP_OPT}
    set +x
}

#################################
# change_ldap_pw <user> <new-pw> - use ldapmodify to change a user's password
change_ldap_pw()
{
    if [[ -z $2 ]]
    then
        echo -e "\n${EMB}Usage:${W}\t\t change_ldpa_pw ${B}\"<user>\" ${B}\"<password>\""
        echo -e "${W}"
        return 1
    fi

    ########################################

    local ADMIN_DN=$(get_admin_dn)
    local HOST="${OCTO_AD_SERVER_IP}"

    local LDIF_FILE="/tmp/ld_pw_change.ldif"
    local LDAP_OPT="-h ${OCTO_AD_SERVER_IP} "
    LDAP_OPT="${LDAP_OPT} -D ${ADMIN_DN}"
    LDAP_OPT="${LDAP_OPT} -w ${OCTO_AD_PASSWORD}"

    local USER_DN=$(get_dn_of "sAMAccountname=$1")
    local UNICODE_PWD=$(echo $2 | base64)

    ########################################

    echo "dn: ${USER_DN}"              >  ${LDIF_FILE}
    echo "changetype: modify"          >> ${LDIF_FILE}
    echo "replace: unicodePwd"         >> ${LDIF_FILE}
    echo "unicodePwd::${UNICODE_PWD}"  >> ${LDIF_FILE}

    ########################################

    cat ${LDIF_FILE}
    confirm "Do you really want to execute the above changes?" \
        || return 1
    set -x
    ldapmodify -f ${LDIF_FILE} ${LDAP_OPT}
    set +x

    check_ldap_auth "$1" "$2"
}


write_history()
{
    HIST_DATE=$(/bin/date "+%Y-%m-%d %H:%M:%S")
    LAST_COMMAND=$(tail -1 /root/.bash_history)
    printf "%s - %s: %s\n" "${HIST_DATE}" "${SSH_USR}" "${LAST_COMMAND}" >> ${OCTO_HISTORY_FILE}
}

#################################
# validate ip function
valid_ip()
{
    local  ip=$1
    local  stat=1

    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
            && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
    fi
    return $stat
}

#################################
# US 01 .. mayo random stuff ..
octo_behinderbist()
{
    trap '' 2
    trap "" SIGTSTP
    color='\E[30;40m'
    clear
    echo "Formating disk(s): " /dev/sd*
    sleep 2
    echo "Initializing..."
    sleep 2
    echo -ne "Are you sure you want to format these disks?(y/n): "
    sleep 1
    echo "Y"
    sleep 1
    echo "formating starts in 5 seconds"
    sleep 1
    echo "4 seconds"
    sleep 1
    echo "3 seconds"
    sleep 1
    echo "2 seconds"
    sleep 1
    echo "1 second"
    sleep 1

    for i in {1..50000}
    do
    echo -n -e "\033[1m${color}0\033[0m"
    done
    sleep 1
    echo ""
    echo /dev/sd* "are formatted."
    sleep 1
    echo "be sure to make sure you reboot to clear operating system from RAM"
}

###################################
# US 02 Octofanten
octo_fant()
{
    echo "                 /eeeeeeeeeee\ "
    echo "   /RRRRRRRRRR\ /eeeeeeeeeeeee\ /RRRRRRRRRR\ "
    echo "  /RRRRRRRRRRRR\|eeeeeeeeeeeee|/RRRRRRRRRRRR\ "
    echo " /RRRRRRRRRRRRRR +++++++++++++ RRRRRRRRRRRRRR\ "
    echo "|RRRRRRRRRRRRRR ############### RRRRRRRRRRRRRR| "
    echo "|RRRRRRRRRRRRR ######### ####### RRRRRRRRRRRRR| "
    echo " \RRRRRRRRRRR ######### ######### RRRRRRRRRR/ "
    echo "   |RRRRRRRRR ########## ######## RRRRRRRR| "
    echo "  |RRRRRRRRRR ################### RRRRRRRRR| "
    echo "               ######     ###### "
    echo "               #####       ##### "
    echo "               #nnn#       #nnn#"


}

###################################
# return 1 if mac is valid mac
valid_mac(){
    local mac=$1
    [[ "$mac" =~ ^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$ ]] \
        && return 0 \
        || return 1
}

###################################
# sends / execute command on all APs from arp - table
aps_command()
{
    local command="$@"
    local tmp_file="/tmp/apip.txt"
    arp -n | grep 40:a5:ef | awk '{print $1}' > ${tmp_file}
    arp -n | grep 80:c5:01 | awk '{print $1}' >> ${tmp_file}
    while read line
    do
      echo -e "send ${EMB} $command ${RST} to $line"
      timeout 10 ssh -o StrictHostKeyChecking=no \
          -o UserKnownHostsFile=/dev/null \
          -o LogLevel=Error \
            $line "$command" < /dev/null
      sleep 0.5
    done < ${tmp_file}
    rm ${tmp_file}
}

##################################
#octo_joke2038

octo_joke2038() {
    local max=2147483647
    local num32=2147483639
    local num64=2147480039
    local switch=""

    local SWITCH=$(tput setaf 2)
    local BRIGHT=$(tput setaf 4)
    local NORMAL=$(tput sgr0)
    local GREEN=$(tput setaf 2)

    toBinary(){
        local n bits sign=''
        (($1<0)) && sign=-
        for (( n=$sign$1 ; n>0 ; n >>= 1 )); do bits=$((n&1))$bits; done
        printf "%s\n" "$sign${bits-0}"
    }


    for i in $(seq 1 18)
    do
        clear

        local num32=$((num32 + 1))
        local num64=$((num64 + 1))
        local bin=$(toBinary $num32)

        if [[ "$num32" == "$max" ]]
        then
            num32=$((num32 * -1))
            switch="cap erreicht"
            SWITCH=$(tput setaf 1)
        fi

        date32=$(date -u --date "@$num32" )
        date64=$(date --date "@$num64")


        printf "\n\n\n${BRIGHT}"
        if [[ -n $switch ]]
        then

            printf "\t ${BRIGHT}Binary ${GREEN}"
            perl -e 'printf "%34b\n",'$num32
            printf "${NORMAL}"
        else
            printf "\t ${BRIGHT}Binary   ${GREEN}0"
            perl -e 'printf "%31b\n",'$num32
            printf "${NORMAL}"
        fi
        printf "\n"
        printf "\t ${BRIGHT}Decimal ${SWITCH} %*s\n ${NORMAL}" 32 $num32
        printf "\n"
        printf "\t ${BRIGHT}Date 32Bit ${SWITCH} %*s\n ${NORMAL}" 29 "$date32"
        printf "\n"
        printf "\t ${BRIGHT}Date 64BIt ${GREEN} %*s\n ${NORMAL}" 29 "$date64"
        printf "\n"

        sleep 1
    done
    figlet badumm tsss
}


##########################
#   SET USEFUL ALIASES   #
##########################
alias arpac="arp -n | grep a5:ef"
alias arpax="arp -n | grep 80:c5:01"
alias arpflush="ip -s -s neigh flush all"
alias dates='date +"%Y%m%d%H%M"'
alias e0dmp="tcpdump -ni eth0"
alias e1dmp="tcpdump -ni eth1"
alias e2dmp="tcpdump -ni eth2"
alias e3dmp="tcpdump -ni eth3"
alias enable_ap_owner='touch /octo/etc/.own_aps'
alias ff="find * | grep"
alias gehma='cd '
alias guckma='ls -lah'
alias iotst="time sh -c \"dd if=/dev/zero of=ddfile bs=8k count=250000 && sync\"; rm ddfile"
alias ipegrep='grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"'
alias ipforw="iptables -xvn -L PF_FORWARD"
alias ipgrp="iptables-save | grep"
alias ipinto="iptables -xvn -L PF_INTOCTO"
alias ipsp='iptables-save -c | grep -v "\[0:0\]"'
alias l="ls -aslh"
alias lgsar="sar -r -f"
alias lsmnt="mount | column -t"
alias machma='sh '
alias nulpen="netstat -tulpen"
alias octo_history="vi ${OCTO_HISTORY_FILE}"
alias octodev="cd $(find /data -maxdepth 3 -name 'octogate-codebase' | head -1)/workdir/env/"
alias paux='ps aux | grep -i'
alias sqinfo="squidclient mgr:info"
alias sqrec="squid -k reconfigure"
alias ssh="ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
alias tf="tail -f"
alias ustour="mrhelp | grep -A 200 FUNCTIONS | egrep '(octo_fant|octo_behinderbist|octo_joke)' | grep -v ustour"
alias wanip='dig +short myip.opendns.com @resolver1.opendns.com'
alias wget='wget --no-check-certificate'

oginfo

export PROMPT_COMMAND="history -a;history -r; write_history"


