Thursday, September 28, 2017

Small Dependency Injection

File: main.php

require 'configure.php';
require 'di.php';
require 'config.php';
require 'db_service.php';
require 'data_model.php';

$db = configure::get('di')->get_service('db');

$data_model = new data_model($db);
$data_model->show_data();

File: configure.php

final class configure {
 /**
  * @var array $config All configured settings handled by this class
  */
 private static $config = array(); 
  
 /**
  * Protected constructor to prevent instance creation
  */
 protected function __construct() { }
 
 /**
  * Fetches a setting set from using Configure::set() or add or update
  *
  * @param string $name The name of the setting to get
  * @param string $key [optional] The Array Key to fetch
  * @return mixed The setting specified by $name, or null if $name was not set
  * 
  * return type: ?array
  */
 public static function get(string $name, $key = false) {
   if (isset(self::$config[strtolower($name)])) {
      $a = self::$config[strtolower($name)];
      if ($key === false) {
         return $a;
      } 
      if (isset($a[$key])) {
         return $a[$key];
      }
   }
   return null;
 }
  
 /**
  * Checks if the setting exists
  *
  * @param string $name The name of the setting to check existance
  * @return boolean true if $name was set, false otherwise
  */
 public static function exists(string $name): bool {
    if (array_key_exists(strtolower($name), self::$config)) {
       return true;
    }
    return false;
 }

  /**
   * Overwrite/Update/Add to $config
   * @param string $name the main key to update
   * @param string $key the sub key
   * @param type $value the data to update
   */
  public static function update(string $name, string $key, $value): void {
 self::$config[strtolower($name)][strtolower($key)] = $value;
  }
  
  /**
   * Add to existing data without loss... to $config
   * @param string $name the main key
   * @param string $key the sub key
   * @param type $value new data to add
   */
  public static function add(string $name, string $key, $value): void {
 self::$config[strtolower($name)][strtolower($key)][] = $value;
  }
    
 /**
  * Frees the setting given by $name, if it exists. All settings no longer in
  * use should be freed using this method whenever possible
  *
  * @param string $name The name of the setting to free
  */
 public static function free(string $name): void {
    if (self::exists($name)) unset(self::$config[strtolower($name)]);
 }
 
 /**
  * Adds the given $value to the configuration using the $name given
  *
  * @param string $name The name to give this setting. Use Configure::exists()
  * to check for pre-existing settings with the same name
  * @param mixed $value The value to set
  */
 public static function set(string $name, $value): void {
    self::$config[strtolower($name)] = $value;
 }
 
}

file: di.php

final class di {
 protected $services = [];
 
 public function register(string $service_name, callable $callable): void {
  $this->services[$service_name] = $callable;
 }
 
 public function get_service(string $service_name, array $args = [] ) {
  if (! array_key_exists($service_name, $this->services)) {
   throw new \Exception("The Service: {$service_name} does not exists.");
  }
  return $this->services[$service_name]($args);
 }
 
 public function __set(string $service_name, callable $callable): void {
  $this->register($service_name, $callable);
 }
 
 public function __get(string $service_name) {
  return $this->get_service($service_name);
 }
 
 public function list_services_as_array(): array { 
  return array_keys($this->services); 
 }
 
 public function list_services_as_string(): string { 
  return implode(',', array_keys($this->services)); 
 }
 
}

configure::set('di', new di());

file: config.php

configure::set('database', array(
  'TYPE' => 'mysql',
  'HOST' => 'localhost',
  'PORT' => '3306',
  'NAME' => 'MyCoolDB',
  'USER' => 'root',
  'PASS' => 'BatMan55', 
));

file: db_service.php

configure::get('di')->register('db', function() {
 $db_info = configure::get('database');
 $db_socket = (isset($db_info['SOCKET'])) ? $db_info['SOCKET'] : false;
 $db_conn = (! empty($db_socket)) ? ":unix_socket={$db_socket};" : "host={$db_info['HOST']};";
 $dsn = "{$db_info['TYPE']}:{$db_conn}port={$db_info['PORT']};dbname={$db_info['NAME']}";
 return new \pdo($dsn, $db_info['USER'], $db_info['PASS']);
});

file: data_model.php

class data_model {

 private $db;
 
 public function __construct(PDO $db) {
  $this->db = $db;
 }
 
 public function show_data(): void {
  $q = $this->db->query("SELECT `data` FROM `test`");

  foreach($q as $row) {
   echo $row['data'] . "<br>";
  }
 }
 
}

If, you do not want to do a bunch of require statements to load all the code up front...

Try Aura.Di
Please leave a comment below, how do you use DI with a framework?

Wednesday, September 20, 2017

How to use my "Auto Git" for Linux

The scripts used here are all valid for Linux...
Sorry, Windows users. I just don't use Windows...
I'm not sure if any of this will apply for Mac users...?
First, create your code and setup git...then create the Repository/git init.... seek online help if you've never done this. GitHub - Start a new git repository

Create the files: gpull, gpull-and-push, and do_git from the posts I made...here. Add them to the folder: /usr/local/bin

nano /usr/local/bin/gpull
nano /usr/local/bin/gpull-and-push
nano /usr/local/bin/do_git
Note: that I did not give the files any file extension. Do not add the .sh unless you update the source file do_git to reflect those changes! Do:
chmod +x /usr/local/bin/gpull
chmod +x /usr/local/bin/gpull-and-push
chmod +x /usr/local/bin/do_git

Now, from Ubuntu Mate. Click System. Click Preferences. Click Look and Feel.
Then, click Main Menu.

Create a New Menu. Name it Git. With the menu Git Selected...Create New Items for each of your git Projects...

Click New Item. Launcher Properties: Type: Application in Terminal.
Name: Your Git Project Folder Name.
Command: /usr/local/bin/do_git "/var/www/PROJECTFOLDERwithGIT"
Click Close.

If, you do not want to install Mate, create an Desktop/Menu folder using your system... See: how-to-create-a-desktop-shortcut for Ubuntu
Add a new Feature to your code base....

Try it out...Click Applications. Click Git. Click Git Project Folder Name.

Follow the on-screen instructions....:
Your git project path will be displayed first.
Along with all branches created.
Type 0 and Press the Enter Key.
Type 2 and Press Enter.

A list of your files will appear.

-If your source code file was Modified an M will appear before the filename.

-If an ?? appears before the filename, it must be added, so Type 2 and then enter the path and filename as it was displayed in the files list. Press enter after typing in the path/file.

Now, type 0 and Press the Enter key.

Another file list appears. Your file should be listed with an M in front of it.
If it has an ??, you can add all un-tracked files by typing yes and then Enter.
Otherwise, type no and press Enter.

Are you feature complete: Type yes and press Enter. So, it does the update.
Enter a commit message and press Enter.

Follow the instructions to do a Pull first.

If you SSH for git to work and have a password, enter it....

Follow the instructions to do a Push now.

If all worked out, the message: Super job! will be shown now press Enter to exit. That's it, all done.
I found, this gem while searching for code online: 
Bonus: GIT COLORS for BASH PROMPT: See link below: 
Scott Woods - Git Prompt 
Git Colors - Based on work by halbtuerke and lakiolen. Thanks, Scott...

Tuesday, September 19, 2017

.bash_aliases - Common Lazy Admin Stuff


# print this months calendar out
cal
# print date and time
# date +"%A, %B %-d, %Y"
#print OS + CPU
uname -rvp

# List these alias Commands, this file...
alias commands='nice -n 17 less ~/.bash_aliases'

#Check if Root
if [ $UID -ne 0 ]; then
    # This is not a root user: 
    echo "Welcome, " `whoami`
    echo "This is a protected system! All access is logged." 
    alias reboot='sudo reboot'
    alias upgrade='sudo apt-get upgrade'
else 
    # Wow, got root:  
    echo "You are logged in as an admin becareful! This is a restricted system, this will be logged."
    alias upgrade='apt-get upgrade'
fi

#cheat-sheet
chmod-cheat() {
echo "chmod =:"
echo "1 = execute only"
echo "2 = write only"
echo "3 = write and execute (1+2)"
echo "4 = read only"
echo "5 = read and execute (4+1)"
echo "6 = read and write (4+2)"
echo "7 = read and write and execute (4+2+1)"
echo "qmod =:"
echo "web) 0644"
echo "safe) 0640"
echo "sbin) 0110"
echo "bin) 0111"
echo "exe) 0111"
echo "+w) 0660"
echo "fullwrite) 0666" 
echo "readonly) 0440"
echo "+777) 777"
}
qmod() {
 if [ -e "$2" ]; then
   if [ -n "$1" ]; then
     if [ -d "$2" ] && [ "$3" == "-R" ]
    then
          OPTION="-R"
  else
          OPTION=""
     fi   
     case $1 in
      web) /bin/chmod $OPTION 0644 "$2" ;;
      safe) /bin/chmod $OPTION 0640 "$2" ;;
      sbin) /bin/chmod $OPTION 0110 "$2" ;;
      bin) /bin/chmod $OPTION 0111 "$2" ;;
      exe) /bin/chmod $OPTION 0111 "$2" ;;
      +w) /bin/chmod $OPTION 0660 "$2" ;;
      fullwrite) /bin/chmod $OPTION 0666 "$2" ;; 
      readonly) /bin/chmod $OPTION 0440 "$2" ;;
      +777) /bin/chmod $OPTION 777 "$2" ;;
      777) echo "are you sure? If so, do chmod +777 file" ;;
      *) /bin/chmod $OPTION $1 "$2" ;;
     esac   
   fi
 else   
   if [ ! -e "$1" ]; then
    echo qmod "$1" file/folder does not exists
   else
    chmod-cheat
   fi 
 fi    
}

#git
alias gs='git status'
alias gc='git commit -a -m'
alias mpull='git pull origin master'
alias mpush='git push origin master'
alias pull='git pull origin'
alias push='git push origin'
alias gb='git branch'
alias branch='git branch'
alias clone='git clone'
alias checkout='git checkout'
#alias gitolite='git clone gitolite:'

#tar
maketar() {
 if [ -e "$1" ]; then
  tar cvzf "$1.tgz" "$@"
 else
   if [ -e "$2" ]; then
    x="" 
    for var in "$@"
    do
      if [ -e "$var" ]; then
        x+=$var
        x+=" "
      fi  
    done
    tar cvzf "$1.tgz" $x
   else
    if [ -n "$1" ]; then
      tar cvzf "$1.tgz" *
    else
      tar cvzf all.tgz *
    fi    
   fi 
 fi
} 

bk() {
 tar cvzf "$1".$(date +%Y%m%d-%H%M%S).tgz "$1"
}

alias untar='tar xvf'
alias ungz='tar xvfz'

#RSYNC
alias backup="nice -n 17 rsync --progress -ravz"

#apt-get
alias agi='sudo apt-get install'
alias agr='sudo apt-get remove'
alias agu='sudo apt-get update'
alias acs='apt-cache search'

#programming
alias c='g++ -std=c++11'
alias c14='g++-4.9 -std=c++14 -pedantic -Wall -I /opt/boost_1_55_0'
alias boost='c++ -I /opt/boost_1_55_0'
# Free Basic Compiler
alias qb='fbc -lang qb '

#Networking
alias public-ip='dig +short myip.opendns.com @208.67.222.222 @208.67.220.220'
alias myip='/bin/ip -4 addr'
alias mymac='/sbin/ifconfig -a'
alias quickping='time ping -c 5'
alias fastping='ping -c 100 -i .250 -s .2'
# Lists all open UDP/TCP ports
alias ports='netstat -tulanp'

# Wake up remote PC/Sever
alias ipwake='/usr/bin/wakeonlan -i'
alias wake='echo "WakeOnLAN File with MAC and IP" && /usr/bin/wakeonlan -f'

# Firewall
alias ipt='sudo /sbin/iptables'
# Display all firewall rules
alias iptlist='sudo /sbin/iptables -L -n -v --line-numbers'
alias iptlistin='sudo /sbin/iptables -L INPUT -n -v --line-numbers'
alias iptlistout='sudo /sbin/iptables -L OUTPUT -n -v --line-numbers'
alias iptlistfw='sudo /sbin/iptables -L FORWARD -n -v --line-numbers'
alias firewall=iptlist

#More Networking
export LAN='eth0'
export WAN='eth1'
alias dnstop='dnstop -l 5 "$LAN"'
alias vnstat='vnstat -i "$LAN"'
alias iftop='iftop -i "$LAN"'
alias tcpdump='tcpdump -i "$LAN"'
alias ethtool='ethtool "$LAN"'

export SN=`netstat -nr | grep -m 1 -iE 'default|0.0.0.0' | awk '{print \$2}' | sed 's/\.[0-9]*$//' `
alias find-servers='nmap --top-ports 10 "$SN".*'
alias find-web-servers='nmap -p 80,443,8080  "$SN".*'
alias find-file-servers='nmap -p 137,138,139,445 "$SN".*'
alias find-ssh-servers='nmap -p 22 "$SN".*'
alias find-ftp-servers='nmap -p 21 "$SN".*'

# Get Wireless Status
alias iwconfig='iwconfig wlan0'
alias wifi=iwconfig

#Ping Default Gateway
export GW=`netstat -nr | grep -m 1 -iE 'default|0.0.0.0' | awk '{print $2}'`
alias check-intenet='ping -c 5 -i .250 -s .2 "$GW"'

#Reboot routers
rebootlinksys() {
 curl -u "admin:$2" "http://$1/setup.cgi?todo=reboot"
}

rebootnetgear() {
 wget --output-document=/dev/null --user="admin" --password="$2" "http://$1/setup.cgi?next_file=diag.htm&todo=reboot"
}

ssh-reboot() {
  if [ -n "$2" ]; then
    ssh "$1"@"$2" sudo -S /sbin/reboot
  else
    ssh "root@$1" /sbin/reboot
  fi  
}

# misc functions
function extract {
 if [ -z "$1" ]; then
    # display usage if no parameters given
    echo "Usage: extract ."
 else
    if [ -f $1 ] ; then
        NAME=${1%.*}
        case $1 in
          *.deb)       echo Installing deb package   ;;
          *.rpm)       echo Installing rpm package   ;;          
          *)           mkdir $NAME && cd $NAME       ;;
        esac

        case $1 in
          *.deb)       sudo nice -n 17 dpkg -i $1       ;;
          *.rpm)       sudo nice -n 17 rpm -ivh $1      ;;          
          *.tar.bz2)   nice -n 17 tar xvjf ../$1        ;;
          *.tar.gz)    nice -n 17 tar xvzf ../$1        ;;
          *.tar.xz)    nice -n 17 tar xvJf ../$1        ;;
          *.lzma)      nice -n 17 unlzma ../$1          ;;
          *.bz2)       nice -n 17 bunzip2 ../$1         ;;
          *.rar)       nice -n 17 unrar x -ad ../$1     ;;
          *.gz)        nice -n 17 gunzip ../$1          ;;
          *.tar)       nice -n 17 tar xvf ../$1         ;;
          *.tbz2)      nice -n 17 tar xvjf ../$1        ;;
          *.tgz)       nice -n 17 tar xvzf ../$1        ;;
          *.zip)       nice -n 17 unzip ../$1           ;;
          *.Z)         nice -n 17 uncompress ../$1      ;;
          *.7z)        nice -n 17 7z x ../$1            ;;
          *.xz)        nice -n 17 unxz ../$1            ;;
          *.exe)       nice -n 17 cabextract ../$1      ;;
          *)           echo "extract: '$1' - unknown archive method" ;;
        esac
    else
        echo "$1 - file does not exist"
    fi
fi
}

function fawk {
    first="awk '{print "
    last="}'"
    cmd="${first}\$${1}${last}"
    eval $cmd
}

# Is gzip working?
function is_gzip {
  curl -I -H 'Accept-Encoding: gzip,deflate' $1 |grep "Content-Encoding"
}

#misc linux
alias hg='history|grep'
alias changed-files='find . -mtime -30 | less'
search() {
  find . -name "$1" -print
}
match() {
  echo "usage: match search_for_pattern file/files" 
  grep -n "$@" | less
}
abc() {
  if [ -n "$2" ]; then
    sort "$1" | grep "$2"
  else
    sort "$1"
  fi  
}
short-asc() {
  abc "$@" | head
}
alias short='sed 100q'
view-long() {
  sed 500q $1 | less
}
save-long() {
  if [ -n "$2" ]; then
    sed 500q $1 > $2
  else
    echo "example: save-long in-file out-file"
  fi
}
head-log() {
  if [ -n "$2" ]; then
    head -n 2000 $1 > $2
  else
    head -n 2000 $1 | less
  fi
}
tail-log() {
  if [ -n "$2" ]; then
    tail -n 2000 $1 > $2
  else
    tail -n 2000 $1 | less
  fi
}  
alias cp='cp -iv'
alias mv='mv -iv'
alias rm='rm -I --preserve-root'
alias la='ls -alh'
mybackup() {
  backup $@ ~/MyBackups/
}
alias documents='cd ~/Documents'
alias downloads='cd ~/Downloads'
alias desktop='cd ~/Desktop'
alias music='cd ~/Music'
alias videos='cd ~/Videos'
alias photos='cd ~/Pictures'
alias cd.='pwd'
alias cd..='cd ..'
alias cd,,='cd ..'
alias ..='cd ..'
alias ,,='cd ..'
alias ...='cd ../..'
alias up2='cd ../..'
alias up3='cd ../../..'
alias up4='cd ../../../..'
alias n='nano'
g() {
  geany $1 &
}
alias e='exit'
alias bye='exit'
alias s='sudo -i'
mcd() {
    mkdir -p $1
    cd $1
}
link-file() {
  if [[ -n "$1" && -n "$2" && -f "$1" && ! -f "$2" ]]; then
    ln -s "$1" "$2"
  else
    echo "link /home/user/source_FILE /opt/new_link"  
  fi
}

link-dir() {
  if [[ -n "$1" && -n "$2" && -d "$1" && ! -f "$2" ]]; then
    ln -s "$1" "$2"
  else
    echo "link /home/user/source_DIR /opt/new_link"  
  fi
}
alias findblanks='sudo awk -F: '\''($2 == "") {print}'\'' /etc/shadow'
alias findrootusers='sudo awk -F: '\''($3 == "0") {print}'\'' /etc/passwd'
alias lock='gnome-screensaver-command --lock'
alias mounted='mount | column -t'
alias md='mkdir -p'
alias o='less'
# wget -c will resume getting a partially-downloaded file.
alias wget='wget -c'

#Maintance
alias cleantmp='find /tmp -atime +3 -exec rm -f {} ";"'

#Web
alias chrome='/opt/google/chrome/chrome'
#my default browser 
alias web=chrome

#CPU and Memory useage
# pass options to free  
alias meminfo='free -m -l -t'

#File Useage
# Disks and File System useage 
alias df='df -H'
# Disk Usage for a folder in useful sizes
alias du='du -ch'
alias disks=df
alias useage=du
alias home='echo "Please wait... Calculating Size of Home..." && du -s /home'
 
# get top process eating memory
alias psmem='ps auxf | sort -nr -k 4'
alias psmem10='ps auxf | sort -nr -k 4 | head -10'
 
# get top process eating cpu
alias pscpu='ps auxf | sort -nr -k 3'
alias pscpu10='ps auxf | sort -nr -k 3 | head -10'

# Get server cpu info 
alias cpuinfo='lscpu'

#Debug Web Server
alias errors=ap_errors
alias ap_errors='tail /var/log/apache2/error.log'
alias hh_errors='tail /var/log/hhvm/error.log'
alias ng_errors='tail /var/log/nginx/error.log'
# Get web server headers #
alias header='curl -I'
# Find out if remote server supports gzip / mod_deflate or not #
alias headerc='curl -I --compress'

# Controll Web Servers
alias a2='sudo service apache2 restart'
alias hh_restart='sudo service hhvm restart'
alias t7='sudo /etc/init.d/tomcat7 restart'
alias phpstatus='service php5-fpm status'
alias phpstart='service php5-fpm start'
alias ngreload='sudo /usr/sbin/nginx -s reload'
alias ngtest='sudo /usr/sbin/nginx -t'
alias lightyload='sudo /etc/init.d/lighttpd reload'
alias lightytest='sudo /usr/sbin/lighttpd -f /etc/lighttpd/lighttpd.conf -t'
alias httpdreload='sudo /usr/sbin/apachectl -k graceful'
alias httpdtest='sudo /usr/sbin/apachectl -t && /usr/sbin/apachectl -t -D DUMP_VHOSTS'

#Windows to linux
alias attrib='chmod'
alias chdir='cd'
alias copy='cp'
alias del='rm'
alias deltree='rm -r'
alias dir='/bin/ls $LS_OPTIONS --format=vertical'
alias edit='nano'
alias ff='whereis'
alias mem='top'
alias move='mv'

## You should use these on servers instead of default commands...!!
#set nice levels for common commands
alias ncfg='nice -n 2 ./configure'
alias nmake='nice -n 2 make'
alias nmakeinstall='sudo nice -n 2 make install'
alias ncp='nice -n 17 cp -iv'
alias nmv='nice -n 17 mv -iv'
alias nrm='nice -n 17 rm -I --preserve-root'
alias ncurl='nice -n 17 curl'
nmaketar() {
 if [ -e "$1" ]; then
  nice -n 17 tar cvzf "$1.tgz" "$@"
 else
   if [ -e "$2" ]; then
    x="" 
    for var in "$@"
    do
      if [ -e "$var" ]; then
        x+=$var
        x+=" "
      fi  
    done
    nice -n 17 tar cvzf "$1.tgz" $x
   else
    if [ -n "$1" ]; then
      nice -n 17 tar cvzf "$1.tgz" *
    else
      nice -n 17 tar cvzf all.tgz *
    fi    
   fi 
 fi
} 
alias ntar='nice -n 17 tar'
alias nungz='nice -n 17 tar xvfz'
alias nuntar='nice -n 17 tar xvf'
alias nl='nice -n 17 ls --color=auto -alh'
alias nn='nice -n 17 nano'
ng() {
  nice -n 17 geany $1 &
}
alias no='nice -n 17 less'
alias nless='nice -n 17 less'
alias ngrep='nice -n 17 grep --color=auto'
alias nhg='history | nice -n 17 grep --color=auto'
#RSYNC
alias nbackup="nice -n 2 rsync --progress -ravz"
alias nrsync="nice -n 2 rsync"
#apt-get
alias nagi='sudo nice -n 2 apt-get install'
alias nagr='sudo nice -n 2 apt-get remove'
alias nagu='sudo nice -n 2 apt-get update'
alias nacs='nice -n 2 apt-cache search'
#git
alias ngs='nice -n 17 git status'
alias ngc='nice -n 17 git commit -a -m'
alias nmpull='nice -n 17 git pull origin master'
alias nmpush='nice -n 17 git push origin master'
alias npull='nice -n 17 git pull origin'
alias npush='nice -n 17 git push origin'
alias ngb='nice -n 17 git branch'
alias nbranch='nice -n 17 git branch'
alias nclone='nice -n 17 git clone'
alias ncheckout='nice -n 17 git checkout'

# useage up 3 cd ../../..
up(){
  local d=""
  limit=$1
  for ((i=1 ; i <= limit ; i++))
    do
      d=$d/..
    done
  d=$(echo $d | sed 's/^\///')
  if [ -z "$d" ]; then
    d=..
  fi
  cd $d
}

gpull-and-push GIT Pull & Push Script


#!/bin/bash
clear
if [ -z "$1" ];  then
 /bin/echo "Please enter you GIT Folder"
 exit 1
else 
 cd "$1"
 /usr/bin/git status -s
 branch=$(git symbolic-ref --short -q HEAD)
 branch=${branch:-HEAD}
 /bin/echo "Did you see any files that you must first add using: git add file ?"
 /bin/echo "Please type: yes/no (then hit enter). yes will add the files, no will skip them."
 read safe
 if [ $safe = yes ]; then
  /usr/bin/git add --all .
 else 
  if [ $safe = no ]; then
   echo "Ok"
  else
   exit 1
  fi
 fi 
 /bin/echo "Are you feature complete and working?"
 /bin/echo "Please type: yes (then hit enter), to do a git pull/push to make $1 up to date!"
 read agree
 if [ $agree = yes ]; then 
  /bin/echo "Please enter your commit message now: What features are added/removed?"
  while :
  do
   read commit
   LEN=$(echo ${#commit})
   if [ $LEN -lt 5 ];  then
    /bin/echo "Please enter your a commit message! What did you work on?"
   else
    break
   fi 
  done
  /usr/bin/git commit -a -m "$commit"
  if [ $? -eq 0 ]; then
   /bin/echo "I applied your commit message, $commit"
  else
   /bin/echo "Opps"
   read -n 1 -p "Hit a key to abort!"
   exit 1
  fi
  /usr/bin/git status
  read -n 1 -p "Ready to pull in new code? Hit any key..."
  /usr/bin/git pull origin $branch
  if [ $? -eq 0 ]; then
   /bin/echo "done with pulling."
  else
   /bin/echo "Opps"
   read -n 1 -p "Hit a key to abort!"
   exit 1
  fi
  /bin/echo "Ready to save your work"
  read -n 1 -p "Press any key to continue..."
  /usr/bin/git push origin $branch
  if [ $? -eq 0 ]; then
   /bin/echo "Super job!"
  else
   /bin/echo "Opps"
   read -n 1 -p "Hit a key to abort!"
   exit 1
  fi
  #/bin/echo "Update Project?"
  #/bin/echo "Have you tested this yet? If working, type: yes (then hit enter)."
  # read worked
  #if [ $worked = yes ]; then
  # /usr/bin/ssh -t project "cd /home/bob/project; /usr/bin/git pull origin master"
  # /bin/echo "thanks"
  #fi
  read -n 1 -p "Press any key to exit"
  /bin/echo ""
  exit 0
 else
  /bin/echo "Skipped update..."
  read -n 1 -p "Press any key to continue..."
  /bin/echo ""
  exit 1
 fi
fi

gpull.sh - Do GIT PULL


#!/bin/bash
clear
if [ -z "$1" ];  then
 /bin/echo "Please enter you GIT Folder"
 exit 1
else 
 /bin/echo "Warning: All local code, in $1, on this PC will be wiped out!!!"
 /bin/echo "Please type: yes (hit enter), to do a git pull to make your local copy up to date!"
 read agree
 if [ $agree = yes ]; then 
  cd "$1"
  branch=$(git symbolic-ref --short -q HEAD)
  branch=${branch:-HEAD}
  /usr/bin/git pull origin $branch
  if [ $? -eq 0 ]; then
   /bin/echo "Updated..."
   read -n 1 -p "Press any key to continue..."
  else
   /bin/echo "Error!!!!"
   read -n 1 -p "Hit a key..."
   exit 1
  fi
  /bin/echo "thanks"
 else
   /bin/echo "Skipped update..."
  read -n 1 -p "Press any key to continue..."
  /bin/echo ""
 fi
fi

do_git.sh - Script to use GIT


#!/bin/bash
if [ -z "$2" ]; then
  FOLDER="$1"
elif [ $2 = home ]; then
  FOLDER="$HOME/$1"
else
  FOLDER="$1"
fi
if [ -d "$FOLDER/.git" ]; then
  cd "$FOLDER"
  /bin/echo "$FOLDER"
  /bin/echo "Here are all the Branches:"
  /usr/bin/git branch -a
  /bin/echo "(0) or (stay) Stay here"
  /bin/echo "(1) or (change) Change to another existing Branch"
  /bin/echo "(2) or (new) Create new Branch"
  read branch
  if [[ -z "$branch" ]]; then
    exit 1
  elif [ $branch = 1 ] || [ $branch = change ]; then
    /bin/echo "Enter name of branch"
    read name
    if [[ -z "$name" ]]; then
      exit 1
    fi
    /usr/bin/git checkout "$name"
    if [ $? -ne 0 ]; then
      echo "Sorry, that branch does NOT exist!"
      exit 1
    fi  
    
  elif [ $branch = 2 ] || [ $branch = new ]; then
    /bin/echo "Enter name for new branch"
    read name
    if [[ -z "$name" ]]; then
      exit 1
    fi
    /usr/bin/git checkout -b "$name"
    if [ $? -eq 0 ]; then
      /usr/bin/git push -u origin HEAD
    else 
      /bin/echo "Unable to make new branch"
      exit 1  
    fi
  fi
  /bin/echo "(1) or (pull) Just Pull and Wipe my code. Run only before changes!"
  /bin/echo "(2) or (push) Will Pull and Push when your Feature Complete!"
  read well
  if [[ -z "$well" ]]; then
      exit 1
  elif [ $well = 1 ] || [ $well = pull ]; then
    /usr/local/bin/gpull "$FOLDER"
  elif [ $well = 2 ] || [ $well = push ]; then
  while :
   do
    /bin/echo "Here are your untracked/unstaged/changed...files:"
    /usr/bin/git status -s
    /bin/echo "(0) Continue on to next step."
    /bin/echo "(1) (discard) Discard changes made in file!"
    /bin/echo "(2) (add) Add file to be staged."
    /bin/echo "(3) (remove) Remove file so it's not staged."
    read todo
    if [[ -z "$todo" ]]; then
      exit 1
    elif [ $todo = 1 ] || [ $todo = discard ]; then
      /bin/echo "enter path/file:"
      read filename
      if [[ -z "$filename" ]]; then
        exit 1
      fi
      /usr/bin/git checkout -- "$filename"
    elif [ $todo = 2 ] || [ $todo = add ]; then
      /bin/echo "enter path/file:"
      read filename
      if [[ -z "$filename" ]]; then
        exit 1
      fi      
      /usr/bin/git add "$filename"
    elif [ $todo = 3 ] || [ $todo = remove ]; then
      /bin/echo "enter path/file:"
      read fiilename
      if [[ -z "$filename" ]]; then
        exit 1
      fi      
      /usr/bin/git rm --cached "$filename"
    elif [ $todo = 0 ]; then
      break
    fi
   done
    /usr/local/bin/gpull-and-push "$FOLDER"
  fi
else
  /bin/echo "Sorry, Git Repo not found!"
fi

Adding new Web Developer Users - dev_user.sh


#!/bin/bash
#Check if Root
if [ $UID -ne 0 ]; then
  echo "Please sudo first....!"
  exit
else
  if [ -z "$1" ]; then
    echo "Enter username"
  else 
    adduser $1 
    usermod -a -G sudo $1
    usermod -g www-data $1
    su - $1
    git config --global core.editor nano
    /bin/echo "Enter Full Name:"
    read fullname
    git config --global user.name "$fullname"
    /bin/echo "Enter Email Address:"
    read email
    git config --global user.email "$email"
  fi
fi  

Make Grub Loader - Show Bootup Messages

user@ubuntu:~# sudo nano /etc/default/grub

Find the line starting with GRUB_CMDLINE_LINUX_DEFAULT and remove the parameters quiet and splash.

When making the changes permanent find the commented line "#GRUB_GFXMODE=640x480" and both remove the beginning "#" so it is no longer a comment and set its value to "text".


# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n 'Simple configuration'

GRUB_DEFAULT=0
GRUB_HIDDEN_TIMEOUT=0
GRUB_HIDDEN_TIMEOUT_QUIET=true
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT=""
GRUB_CMDLINE_LINUX=""

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL=console

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'
GRUB_GFXMODE=text

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux
#GRUB_DISABLE_LINUX_UUID=true

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"
user@ubuntu:~# sudo update-grub

post_install.sh for PHP7.1, and misc Goodies



#!/bin/bash

#Check if Root
if [ $UID -ne 0 ]; then
  echo "Please sudo first....!"
  exit
else
  add-apt-repository ppa:ondrej/php
  apt-get update
  apt-get -y install dpkg-dev
  apt-get -y install build-essential
  apt-get -y install curl
  apt-get -y install screen
  apt-get -y install wget
  apt-get -y install apache2 
  apt-get -y install apache2-utils
  a2enmod rewrite
  apt-get -y install mysql-server
  mysql_secure_installation
  apt-get -y install php7.1 php7.1-cli php7.1-dev php7.1-common
  apt-get -y install php7.1-mbstring php7.1-mysql php7.1-gd php7.1-json 
  apt-get -y install php7.1-xml php7.1-xmlrpc php7.1-zip php7.1-sqlite3
  phpenmod mbstring
  # apt-get -y install libapache2-mod-php7.1
  apt-get -y install phpmyadmin
  apt-get -y install nano
  apt-get -y install geany
  apt-get -y install git
  apt-get -y install keepass2
  apt-get -y install gimp
  apt-get -y install filezilla
  apt-get -y install openjdk-7-jre
  apt-get -y install oracle-java8-installer
  #Remove Remove suid bits
  chmod -s /bin/fusermount 
  chmod -s /bin/mount 
  chmod -s /bin/su 
  chmod -s /bin/umount 
  chmod -s /usr/bin/bsd-write 
  chmod -s /usr/bin/chage 
  chmod -s /usr/bin/chfn 
  chmod -s /usr/bin/chsh 
  chmod -s /usr/bin/mlocate 
  chmod -s /usr/bin/mtr 
  chmod -s /usr/bin/newgrp 
  chmod -s /usr/bin/traceroute6.iputils 
  chmod -s /usr/bin/wall
  chmod 700 /root
  chmod 600 /etc/crontab
  chmod 700 /var/crash
  chown -R root:root /var/crash
  chmod 740 /etc/rc.d/init.d/iptables
  chmod 740 /sbin/iptables
  chmod 740 /usr/share/logwatch/scripts/services/iptables
  chmod -R 700 /etc/skel
  chmod 640 /etc/syslog.conf
  chmod 640 /etc/security/access.conf
  chmod 600 /etc/sysctl.conf
  #Disable un-needed services
  #/sbin/chkconfig bluetooth off
  /sbin/chkconfig irda off
  /sbin/chkconfig lm_sensors off
  /sbin/chkconfig portmap off
  /sbin/chkconfig rawdevices off
  /sbin/chkconfig rpcgssd off
  /sbin/chkconfig rpcidmapd off
  /sbin/chkconfig rpcsvcgssd off
  /sbin/chkconfig sendmail off
  /sbin/chkconfig xinetd off
  /sbin/chkconfig kudzu off
  #Disable un-needed users
  /usr/sbin/userdel shutdown
  /usr/sbin/userdel halt
  /usr/sbin/userdel games
  /usr/sbin/userdel operator
  /usr/sbin/userdel ftp
  /usr/sbin/userdel news
  /usr/sbin/userdel gopher
  #install npm
  cd /usr/local/bin
  apt-get -y install npm
  apt-get -y install nodejs-legacy
  npm install -g npm
  npm install -g n
  n stable
  npm install --global gulp-cli
  #Doxygen PHP Documentor
  apt-get -y install doxygen
  #PHP Composer
  cd /tmp
  wget -O composer-setup.php https://getcomposer.org/installer

/usr/bin/php composer-setup.php --filename=composer --install-dir=/usr/local/bin

  rm composer-setup.php
  #PHPUnit
  wget -O phpunit https://phar.phpunit.de/phpunit.phar
  chmod +x phpunit
  mv phpunit /usr/local/bin/
  #MS Fonts

wget http://ftp.de.debian.org/debian/pool/contrib/m/msttcorefonts/ttf-mscorefonts-installer_3.6_all.deb -P ~/Downloads

  apt -y install ~/Downloads/ttf-mscorefonts-installer_3.6_all.deb
  #install Google Chrome
  mkdir $HOME/.config/google-chrome
  touch "$HOME/.config/google-chrome/First Run"
  cd /tmp
  wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
  sudo dpkg -i google-chrome-stable_current_amd64.deb
  rm -f google-chrome-stable_current_amd64.deb
  #Desktops xfce4
  apt-get -y install xfce4
  # Un-comment the following line: if you do not like UNITY...and understand the risks. 
  #apt-get -y autoremove --purge unity-*
fi

Part 2 Ubuntu Auto Installer

I forgot were I found this online, but here is how to use the ks.cfg file with an auto install...

1. Create Preseed file

Pressed commands work when they are directly written inside the Kickstart file, but I wanted to separate the two files. Create new file on you desktop named ubuntu-auto.seed with the following contents:
# Unmount drives with active partitions. 
Without this command all the installation process would stop and 
require confirmation to unmount drives that are already mounted.
d-i preseed/early_command string umount /media || true

# Don't install recommended items
d-i preseed base-installer/install-recommends boolean false

# Install only security updates automatically
d-i preseed pkgsel/update-policy select unattended-upgrades
For additional Preseed configuration options, refer to official Ubuntu installation guide.

2. Extract original ISO image

Download Ubuntu Server 16.04 x64 from official Ubuntu website and put it on your desktop. It is necessary to use server version, because desktop version doesn't support unattended installations. Desktop functionality will work after ubuntu-desktop package in %packages section of kb.cfg file is installed.
Mount the .iso file to Ubuntu filesystem. The commands below will mount .iso file to the folder named ubuntu_iso:
cd ~/Desktop
mkdir ubuntu_iso
sudo mount -r -o loop ubuntu-16.04.1-server-amd64.iso ubuntu_iso
Copy .iso contents to another folder on your desktop so we can edit the files. Don't forget to set the right permissions to be able to make changes.
mkdir ubuntu_files
rsync -a ubuntu_iso/ ubuntu_files/
sudo chown ernestas:ernestas ubuntu_files
sudo chmod 755 ubuntu_files
sudo umount ubuntu_iso
rm -rf ubuntu_iso

3. Edit contents of ISO image

Copy ks.cfg, ubuntu-auto.seed and post.sh files to newly created ubuntu_files folder
cp {ks.cfg,ubuntu-auto.seed,post.sh} ubuntu_files
chmod 644 ubuntu_files/ks.cfg ubuntu_files/ubuntu-auto.seed
chmod 744 ubuntu_files/post.sh
Change isolinux folder and isolinux/txt.cfg permissions for editing:

chmod 755 ubuntu_files/isolinux ubuntu_files/isolinux/txt.cfg ubuntu_files/isolinux/isolinux.cfg

Now we need to make the installer read Kickstart and Preseed files by including new menu selection for automatic Ubuntu installation. To do this edit txt.cfg in isolinux folder:
nano ubuntu_files/isolinux/txt.cfg
Paste the following content right after the line containing default install:
label autoinstall
  menu label ^Automatically install Ubuntu
  kernel /install/vmlinuz

append file=/cdrom/preseed/ubuntu-server.seed vga=788 initrd=/install/initrd.gz ks=cdrom:/ks.cfg preseed/file=/cdrom/ubuntu-auto.seed quiet --

Set timeout to start the installation automatically:
sed -i -r 's/timeout\s+[0-9]+/timeout 3/g' ubuntu_files/isolinux/isolinux.cfg
Warning! This command will start installation proccess immediately and format the hard drive as defined in ks.cfg. Skip it if you want to manually start the process after booting into ISO.
Change the permissions back:
chmod 555 ubuntu_files/isolinux
chmod 444 ubuntu_files/isolinux/txt.cfg ubuntu_files/isolinux/isolinux.cfg

4. Recreate ISO image

Create new .iso:

sudo mkisofs -D -r -V "ubuntu-auto" -J -l -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -input-charset utf-8 -cache-inodes -quiet -o ubuntu-auto.iso ubuntu_files/

Remove files:
sudo rm -rf ubuntu_files

5. Optional – Create bootable USB media

Make the .iso file bootable from external USB devices:
sudo apt-get install syslinux-utils
sudo isohybrid ubuntu-auto.iso
Plug in USB device and determine the path to it:
lsblk
My USB device was identified as /dev/sdb. Unmount the media:
sudo umount /dev/sdb
Copy ISO to USB device. Make sure to copy directly to the drive, not the first partition (/dev/sdb
1)

Be-careful that you only DD the USB Stick (that is blank) and not your HD or a different USB stick with data on it! As dd is a powerful low level system tool, use with extreme care.

sudo dd if=ubuntu-auto.iso of=/dev/sdb bs=4M && sync

6. Known Issues

8.1. USB doesn't mount as CD-ROM
Error message:
"Your installation CD-ROM couldn't be mounted. This probably means that the CD-ROM was not in the drive. If so you can insert it and try again."
Fix: Use dd to create bootable USB. Previuosly this error was caused by Ubuntu Startup Disk Creator.

ks.cfg for Ubuntu Auto Installer

#Generated by Kickstart Configurator
#platform=AMD64 or Intel EM64T

#System language
lang en_US
#Language modules to install
langsupport en_US
#System keyboard
keyboard us
#System mouse
mouse
#System timezone
timezone America/Detroit
#Root password
rootpw --disabled
#Initial user
user dev --fullname "Developer" --password Welcome2Guest7Dev
#Reboot after installation
reboot
#Use text mode install
text
#Install OS instead of upgrade
install
#Use CDROM installation media
cdrom
#System bootloader configuration
bootloader --location=mbr
#Clear the Master Boot Record
zerombr yes
#Partition clearing information
clearpart --all --initlabel
#New Disk partitioning information
part /boot --fstype ext4 --size 1200 --asprimary
part pv.01 --size 1 --grow
volgroup mainvg pv.01
logvol swap --fstype=swap --name=swap --vgname=mainvg --recommended
logvol / --fstype=ext4 --name=lv_root --vgname=mainvg --size=1 --grow
logvol /var/log --fstype=ext4 --name=lv_varlog --vgname=mainvg --size=1000
# yes to all...
preseed partman-lvm/device_remove_lvm boolean true
preseed partman/confirm_write_new_label boolean true
preseed partman/confirm boolean true
# needed to answer the 'do you want to write changes to disk"
preseed partman-lvm/confirm_nooverwrite boolean true
# needed to answer the question about not having a separate /boot
preseed partman-auto-lvm/no_boot boolean true
#System authorization infomation
auth  --useshadow  --enablemd5
#Network information
network --bootproto=dhcp --device=eth0
#Firewall configuration
firewall --disabled
#Do not configure the X Window System
skipx
#Package install information
%packages
ca-certificates
openssl
python
vim
ubuntu-desktop
ubuntu-mate-desktop
# Add your custom post installation script here
%post
# Add post installation script to /usr/local/bin/ directory
# Fix locale
echo 'LANG="en_US.UTF-8"' > /etc/default/locale
echo 'LANGUAGE="en_US:en"' >> /etc/default/locale
echo 'LC_ALL="en_US.UTF-8"' >> /etc/default/locale
#User Issue Screen
rm -f /etc/issue /etc/issue.net
cat <<EOT > /etc/notice.txt
***************************************************************************
                            NOTICE TO USERS


This computer system is the private property of its owner, whether
individual, corporate or government.  It is for authorized use only.
Users (authorized or unauthorized) have no explicit or implicit
expectation of privacy.

Any or all uses of this system and all files on this system may be
intercepted, monitored, recorded, copied, audited, inspected, and
disclosed to your employer, to authorized site, government, and law
enforcement personnel, as well as authorized officials of government
agencies, both domestic and foreign.

By using this system, the user consents to such interception, monitoring,
recording, copying, auditing, inspection, and disclosure at the
discretion of such personnel or officials.  Unauthorized or improper use
of this system may result in civil and criminal penalties and
administrative or disciplinary action, as appropriate. By continuing to
use this system you indicate your awareness of and consent to these terms
and conditions of use. LOG OFF IMMEDIATELY if you do not agree to the
conditions stated in this warning.

****************************************************************************
EOT
cp /etc/notice.txt /etc/notice.bak
ln -s /etc/notice.txt /etc/issue
ln -s /etc/notice.txt /etc/issue.net
# Clean
apt-get -f -y install
apt-get -qq -y autoremove
apt-get -y clean

Clean Code is the Documentation

1) Write code that is easy to follow and read.
   a) Keep function blocks under 20 lines. Should only do one thing.
   b) Use descriptive variable/class/method names.
   c) Try to be within 80 columns limit if possible. View code on a tablet/print out, to see if it cuts off.
2) Write your PHP Unit test before you write your code.

3) Function should have no more than three parameters! Avoid passing in arrays, as it is hard to figure out later on what you can pass to the function. Use class objects, instead:

class db_options {
  private $table_name;
....
  public function set_table_name(string $table_name): void { $this->table_name = $table_name; }
  public function get_table_name(): string {
   // IF no Database ticks are around table name then add them
    return (strrpos($this->table_name, "`") === false) ? "`{$this->table_name}`" : $this->table_name;
  }
....
}

class db {
....
  public function run(db_options $db_options) { ......... }
}

$db_options = new db_options();
$db_options->set_table_name('users');
...
$db = new db(pdo $pdo_dsn);
$db->run($db_options);
----------------------------------------------------------------------------------------------------------

4) Avoid Nested IF Statements like this:

if ($exec !== false) {
        if ( $db_options->is_read_mode() ) {
          if ( $db_options->is_fetch_all() ) {

            if (\bla_found_string($this->sql, "SQL_CALC_FOUND_ROWS")) {
              $ret = $pdostmt->fetchAll(PDO::FETCH_ASSOC);
              $fsql = "SELECT FOUND_ROWS() AS totalRows";
              $totalRows = $this->query($fsql)->fetch();
              $this->count = $totalRows[0];
              return $ret;
            } else {
              $this->count = $pdostmt->rowCount();
              return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
            }
          } else {
            return $pdostmt->fetch(PDO::FETCH_ASSOC);
          }
        } elseif ( $db_options->is_write_mode() ) {
          return $pdostmt->rowCount();
        }
      }

Convert into single tabbed IF Statements, that check one condition and return control back early:
  try {
......
      if ($exec === false) {
        return false;
      }
       
      if ( $db_options->is_write_mode() ) {
        return $pdo_stmt->rowCount();
      }
       
      if ( ! $db_options->is_read_mode() ) {
        return false;
      }
     
      if ( $db_options->is_fetch_pdo_stmt() ) {
        return $pdo_stmt;
      }
     
      if ( $db_options->is_fetch_row() ) {
        return $pdo_stmt->fetch(PDO::FETCH_ASSOC);
      }
......