penguin/utils

my env utils

commit 8318550036af4c57791643d9133db5900ee2c63e

author斟酌 鵬兄 <tgckpg@gmail.com>
date2014-01-23T12:48:52Z
subjectSome old stuff
commit 8318550036af4c57791643d9133db5900ee2c63e
Author: 斟酌 鵬兄 <tgckpg@gmail.com>
Date:   2014-01-23T12:48:52Z

    Some old stuff
---
 bash/automail/mailList           |   2 +
 bash/automail/mailListProxy      |   1 +
 bash/automail/mailip             |  61 +++++++++++
 bash/automail/mailpasswd         |  79 ++++++++++++++
 bash/cronbackup/backup.log       |   5 +
 bash/cronbackup/backup.sh        |  79 ++++++++++++++
 bash/cronbackup/backup_err.log   |   0
 bash/cronbackup/backup_list      |   8 ++
 bash/cronbackup/exclude/file.txt |   2 +
 deprecated/bash/amuleComplete.sh |   5 +
 php/pkgstat.php                  |  44 ++++++++
 php/regRename.php                | 228 +++++++++++++++++++++++++++++++++++++++
 12 files changed, 514 insertions(+)

diff --git a/bash/automail/mailList b/bash/automail/mailList
new file mode 100644
index 0000000..ae90ec2
--- /dev/null
+++ b/bash/automail/mailList
@@ -0,0 +1,2 @@
+root
+monkenix@gmail.com
diff --git a/bash/automail/mailListProxy b/bash/automail/mailListProxy
new file mode 100644
index 0000000..93ca142
--- /dev/null
+++ b/bash/automail/mailListProxy
@@ -0,0 +1 @@
+root
\ No newline at end of file
diff --git a/bash/automail/mailip b/bash/automail/mailip
new file mode 100644
index 0000000..6320af1
--- /dev/null
+++ b/bash/automail/mailip
@@ -0,0 +1,61 @@
+#!/bin/bash
+PREVIP=$(cat /opt/utils/StoredIP)
+MAILFILE="Tempfile2"
+TRYCOUNT=10
+while [ TRUE ]; do
+
+  if [ $TRYCOUNT -le 0 ]; then
+    echo Error occured.
+    exit 1
+  fi
+
+  CURRENTIP=$(curl --silent http://checkip.dyndns.org/|grep -Eo '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}')
+  STATUS=$?
+  sleep 5
+  if [ ! $STATUS ]; then
+    let TRYCOUNT-=1
+  elif [ ! "$CURRENTIP" ]; then
+    let TRYCOUNT-=1
+  else
+    break
+  fi
+
+done
+
+if [ "$PREVIP" = "$CURRENTIP" ]
+then
+  exit 0
+fi
+
+touch $MAILFILE
+exec 6>&1
+exec > $MAILFILE
+
+
+
+echo This is an auto generated mail to notify the server IP had updated:
+echo 這是一封自動發送的電郵,以通知服務器地址經已更新:
+echo 
+echo Server Address:
+echo 服務器地址:
+echo $CURRENTIP
+echo 
+echo 
+echo Pleas do not reply to this email.
+echo 請勿回覆。
+echo If you have any questions, please feel free to contact tgckpg@gmail.com
+echo 如有任何疑問,請電郵至tgckpg@gmail.com
+echo 
+echo Regards,
+echo 祝 安康
+echo Penguin 鵬兄
+echo 
+echo 
+
+echo $CURRENTIP > /opt/utils/StoredIP
+
+while read line
+do mutt -s "通知Notice: 服務器地址已變更New address for server." -- $line < $MAILFILE
+done < /opt/utils/mailList
+rm $MAILFILE
+
diff --git a/bash/automail/mailpasswd b/bash/automail/mailpasswd
new file mode 100644
index 0000000..4cfac3e
--- /dev/null
+++ b/bash/automail/mailpasswd
@@ -0,0 +1,79 @@
+#!/bin/bash
+MAILFILE="Tempfile"
+
+TRYCOUNT=10
+while [ TRUE ]; do
+
+  if [ $TRYCOUNT -le 0 ]; then
+    echo Error occured.
+    exit 1
+  fi
+
+  CURRENTIP=$(curl --silent http://checkip.dyndns.org/|grep -Eo '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}')
+  STATUS=$?
+  sleep 5
+  if [ ! $STATUS ]; then
+    let TRYCOUNT-=1
+  elif [ ! "$CURRENTIP" ]; then
+    let TRYCOUNT-=1
+  else
+    break
+  fi
+
+done
+
+
+
+touch $MAILFILE
+exec 6>&1           # Link file descriptor #6 with stdout.
+                    # Saves stdout.
+exec > $MAILFILE     # stdout replaced with file $LOGFILE.
+PSDDLEN=$(((RANDOM % 9) + 16))
+PASS=$( java -jar /opt/utils/pwgen.jar $PSDDLEN )
+htpasswd -b /var/auths/squid proxyuser $PASS
+
+
+echo This is an auto generated mail to notify the password had changed for the proxy server:
+echo 這是一封自動發送的電郵通知,密碼經已變更,登入時請使用新的密碼〔於「」內〕:
+echo Passward \(enclosed in 「」\):
+echo 
+echo 「$PASS」
+echo 
+echo 
+echo Additional Information:
+echo 附加資訊:
+echo 
+echo Server Address:
+echo 服務器地址:
+echo $CURRENTIP
+echo 
+echo Server port:
+echo 服務器端口:
+echo 
+echo 3128
+echo 
+echo 
+echo 
+echo Please be awared that the password will change for each week.
+echo 請留意密碼會每星期變更一次。
+echo 
+echo 
+echo Pleas do not reply to this email.
+echo 請勿回覆。
+echo If you have any questions, please feel free to contact tgckpg@gmail.com
+echo 如有任何疑問,請電郵至tgckpg@gmail.com
+echo 
+echo Regards,
+echo 祝 安康
+echo Penguin 鵬兄
+echo 
+echo 
+echo Password Generator powered by Moonbird.
+
+
+while read line
+do mutt -s "通知Notice: 密碼已變更New pasword for squid proxy server." -- $line < $MAILFILE
+done < /opt/utils/mailListProxy
+
+rm $MAILFILE
+
diff --git a/bash/cronbackup/backup.log b/bash/cronbackup/backup.log
new file mode 100644
index 0000000..839b829
--- /dev/null
+++ b/bash/cronbackup/backup.log
@@ -0,0 +1,5 @@
+Mounting /media/backup_mirror/ ...
+Checking for expired backups blogAPI.git (2)
+Checking for expired backups wenku8.git (2)
+Checking for expired backups wenku8 (4)
+Checking for expired backups file (2)
diff --git a/bash/cronbackup/backup.sh b/bash/cronbackup/backup.sh
new file mode 100644
index 0000000..5d7d861
--- /dev/null
+++ b/bash/cronbackup/backup.sh
@@ -0,0 +1,79 @@
+#!/bin/bash
+
+# IO Redirection
+exec > backup.log
+
+# exec 2> backup_err.log
+
+BAKDIR=/media/backup_mirror
+
+if ! grep -qs $BAKDIR /proc/mounts; then
+	echo Mounting $BAKDIR ...
+	mount $BAKDIR
+fi
+
+
+while read line; do
+
+	# substring first char
+	firstChr=${line::1}
+
+	# if line is not empty and does not start with "#"
+
+	if [ $firstChr ] && [ $firstChr != "#" ]; then
+
+		# file and arguments are seperated by ":"
+		IFS=':' read -ra ARGS <<< "$line"
+		
+		# Get file
+		FILE=${ARGS[0]}
+
+		# if file exists
+		if [ -a $FILE ]; then
+
+			# filename
+			FILENAME=$(basename $FILE)
+		
+			# set the backup name YYYYMMDDhhmm
+			BACKUPFILE=$(date +$FILENAME.%Y%m%d%H%M.tar.gz)
+
+			# exclude file
+			EXCLUDE="exclude/${ARGS[1]}"
+
+			if [ -f $EXCLUDE ]; then
+				tar zcf "$BAKDIR/$BACKUPFILE" -C "$FILE/../" $FILENAME -X $EXCLUDE
+			else
+				tar zcf "$BAKDIR/$BACKUPFILE" -C "$FILE/../" $FILENAME
+			fi
+			
+			# count backup file
+			fCount=$(ls $BAKDIR/*$FILENAME*.gz|wc -l)
+
+			echo Checking for expired backups $FILENAME \($fCount\)
+			
+			# keep up to 7 backup
+			if [ $fCount -ne 7 ]; then
+
+				# delete count
+				dCount=`expr $fCount - 7`
+				
+				# loop over files
+				for files in $BAKDIR/*$FILENAME*.gz; do
+					if [ 0 -lt $dCount ]; then
+						
+						# remove expired file
+						rm "$files";
+						
+						# dCount --
+						dCount=$((dCount-1));
+					fi
+				done
+			fi
+
+		fi
+		
+	fi
+	# echo --\> $line
+done < backup_list
+
+umount $BAKDIR
diff --git a/bash/cronbackup/backup_err.log b/bash/cronbackup/backup_err.log
new file mode 100644
index 0000000..e69de29
diff --git a/bash/cronbackup/backup_list b/bash/cronbackup/backup_list
new file mode 100644
index 0000000..02403a6
--- /dev/null
+++ b/bash/cronbackup/backup_list
@@ -0,0 +1,8 @@
+# git backups
+/srv/repo/blogAPI.git
+/srv/repo/wenku8.git
+/wenku8-android.git
+
+# www
+/var/www/wenku8
+/var/www/file:file.txt
diff --git a/bash/cronbackup/exclude/file.txt b/bash/cronbackup/exclude/file.txt
new file mode 100644
index 0000000..9c8d78a
--- /dev/null
+++ b/bash/cronbackup/exclude/file.txt
@@ -0,0 +1,2 @@
+blog
+public
diff --git a/deprecated/bash/amuleComplete.sh b/deprecated/bash/amuleComplete.sh
new file mode 100644
index 0000000..8d77bb8
--- /dev/null
+++ b/deprecated/bash/amuleComplete.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+cd /opt/utils
+fileName=$(java Main_mod $1)
+cd /media/Misc/Temp
+mv $1 $fileName
diff --git a/php/pkgstat.php b/php/pkgstat.php
new file mode 100644
index 0000000..c225071
--- /dev/null
+++ b/php/pkgstat.php
@@ -0,0 +1,44 @@
+<?php
+
+function delUponExit() {
+	if(is_file('/tmp/php.apt_history.log'))
+			unlink('/tmp/php.apt_history.log');
+}
+register_shutdown_function('delUponExit');
+
+$i = 1;
+exec("ls /var/log/apt/history.log.*.gz", $list);
+foreach($list as $entry) {
+	$lines = gzfile($entry);
+		file_put_contents("/tmp/php.apt_history.log", $lines, FILE_APPEND);
+}
+$list = null;
+exec("cat /var/log/apt/history.log >> /tmp/php.apt_history.log");
+exec('cat /tmp/php.apt_history.log |egrep --regexp=\'^Commandline:\sapt-get\s[(install)(remove)(purge)]\'|awk \'{print $3" "$4}\'', $list);
+$i = 0; $j = 0;
+foreach($list as $entry) {
+	$history=explode(" ", $entry);
+	if($history[0] == "autoremove" || $history[0] == "upgrade")continue;
+	$history[0] == "install" ? ($packages[$history[1]]=true):($packages[$history[1]]=false);
+}
+foreach($packages as $package => $stat) {
+	$stat ? ($ipackage[$i ++] = $package):($rpackage[$j ++] = $package);
+}
+$i = sizeOf($ipackage);
+$j = sizeOf($rpackage);
+
+$l = $i > $j ? $i:$j;
+echo "Custom package activities(apt-get):\n";
+echo "+---------------------------------------------------------+\n";
+echo "|    Package(s) installed    |     Package(s) removed     |\n";
+echo "|----------------------------+----------------------------|\n";
+$ll = .5*(strlen("+---------------------------------------------------------+") - 3);
+for($k = 0; $k < $l; $k ++) {
+$il = str_pad($k < $i ? $ipackage[$k]:"", $ll, " ", STR_PAD_BOTH);
+$rl = str_pad($k < $j ? $rpackage[$k]:"", $ll, " ", STR_PAD_BOTH);
+
+
+echo "|$il|$rl|\n";
+}
+echo "+---------------------------------------------------------+\n";
+?>
diff --git a/php/regRename.php b/php/regRename.php
new file mode 100644
index 0000000..cc0f33c
--- /dev/null
+++ b/php/regRename.php
@@ -0,0 +1,228 @@
+<?php
+
+error_reporting ( E_ALL^E_NOTICE ) ;
+
+//----------- Usage -----------
+
+if ( !$argv[1] ) 
+	die ( "Usage: php {$argv[0]} [options] [-d directory] [-p patterns] [-s \"first match\" \"second\" ...] [...args]\n
+  -d <paths>	Directories to look over
+  -p <patterns>	Define RegEx patterns
+  -r		Rename file recursively
+  -s <str ...>	Strings that will replace the matches
+
+  Optional:
+	*-e <patterns>	Exclude defined pattern
+	*-l <File>	Output log file
+	-t		Test without modifying anything
+
+*Not available yet.
+
+" ) ;
+
+//------- End Usage -----------
+
+
+
+
+//Define globals
+$test = false;
+$recursive = false;
+$searchDirs = array();
+$patterns = array();
+$replaceStrs = array();
+
+//------- Main Functions --------
+function getDirName ( $dir ) {
+	return is_dir ( $dir ) ? $dir : dirname ( $dir ) ;
+}
+
+function getFileList ( $dir ) {
+	$fileList = array();
+	$iterator = new DirectoryIterator ( getDirName ( $dir )  ) ;
+	foreach ( $iterator as $fileinfo ) {
+		if ( $fileinfo->isFile() ) {
+				$fileList[] = $dir."/".$fileinfo->getFilename();
+		}
+	}
+	return $fileList;
+}
+
+function getDirList ( $dir ) {
+	$dirList = array();
+	$iterator = new DirectoryIterator ( getDirName ( $dir )  ) ;
+	foreach ( $iterator as $fileinfo ) {
+			if ( $fileinfo->isDir() ) {
+					$dirList[] = $fileinfo->getFilename();
+			}
+	}
+	//Chop dir "." and ".."
+	array_shift ( $dirList ) ;
+	array_shift ( $dirList ) ;
+	return $dirList;
+}
+
+function getWholeDirList ( $dir ) {
+	$wholeDirList = array();
+	//getWholeDirList will stop untill getDirList return an empty array.
+	foreach ( getDirList ( $dir ) as $file ) {
+			//Store found path
+			$wholeDirList[] = "$dir/$file";
+			//Method getWholeDirList will self-iterate if sub-directories exist.
+			$wholeDirList = array_merge ( $wholeDirList, getWholeDirList ( "$dir/$file" )  ) ;
+	}
+	return $wholeDirList;
+}
+
+function getWholeFileList ( $dir ) {
+	//Get the first level list.
+	$wholeFileList = getFileList( $dir );
+	//getWholeDirList and search its files.
+	foreach ( getWholeDirList ( $dir ) as $dir ) {
+		$wholeFileList = array_merge ( $wholeFileList, getFileList ( $dir )  ) ;
+	}
+	return $wholeFileList;
+}
+
+function validateOptions (  ) {
+	global $searchDirs, $patterns, $replaceStrs;
+	
+	try {
+		if(count($searchDirs) == 0)
+		throw new Exception("Search directory is missing");
+		else if(count($patterns) == 0)
+		throw new Exception("Search pattern is missing");
+		else if(count($replaceStrs) == 0)
+		throw new Exception("Replacement string is missing");
+		else if(count($replaceStrs) != count($patterns))
+		throw new Exception("Replacement string and pattern count not match");
+	} catch(Exception $e) {
+		var_dump( $GLOBALS );
+		die("Error: $e.\n");
+	}
+}
+
+function setOptions( $item, $value = NULL ) {
+	global $test, $recursive, $searchDirs, $patterns, $replaceStrs;
+	switch($item) {
+		case "-d":
+			if($value)
+			$searchDirs[] = $value;
+		break;
+		case "-p":
+			if($value)
+			$patterns[] = $value;
+		break;
+		case "-r":
+			$recursive = true;
+		break;
+		case "-s":
+			if($value)
+			$replaceStrs[] = $value;
+		break;
+		case "-t":
+			$test = true;
+		break;
+		default:
+			//Do nothing
+	}
+}
+
+//parseOptions utilitiese by tgckpg
+function parseOptions ( $argStream, $handler ) {
+	//Chop first useless argument -- argv[0]
+	array_shift ( $argStream ) ;
+	//Initiate ArrayObject for iterator
+	$arrayobject = new ArrayObject ( $argStream ) ;
+	//Initiate iterator for iteration
+	$iterator = $arrayobject->getIterator();
+
+	//If options is set first
+	if( $iterator->valid() && preg_match ( '/^-\w$/', $iterator->current() ) ) {
+		//iterate through whole argument stream
+		for (	; $iterator->valid(); $iterator->next() ) {
+			//Check if reached next option
+			if( preg_match ( '/^-\w$/', $opts = $iterator->current() ) ) {
+				//Get current options
+				$currOpt = $opts;
+				//echo "$currOpt\n";
+				//Test if next stream is an option
+				for ( $iterator->next(); $iterator->valid(); $iterator->next() ) {
+					if ( preg_match ( '/^-\w$/', $opts = $iterator->current() ) ) {
+						//echo "$currOpt $opts\n";
+						$handler($currOpt);
+						$currOpt = $opts;
+					} else break;
+					//var_dump($iterator->valid());
+				}
+			}//End if
+			//echo "$currOpt $opts\n";
+			$handler($currOpt, $opts);
+			//A temporary fix for infinite loop
+			if(!$iterator->valid())
+				break;
+		}// End for
+	//If option is not set first.
+	} else {
+		//Try other approach.
+	}// End if
+}
+
+
+//------- End Main Functions --------
+
+
+parseOptions ( $argv, 'setOptions' ) ;
+validateOptions();
+
+
+//------- Begin Operations -------
+foreach ( $searchDirs as $dir ) {
+	echo "Directory: $dir\nBuilding file list ...\n";
+	if ( $recursive ) {
+		$fileList = getWholeFileList($dir);
+	}	else {
+		$fileList = getFileList($dir);
+	}
+	echo "Searching ...\n";
+	foreach ( $fileList as $file ) {
+		//
+		// Get the file name
+		// RegExplained:
+		// Example: /foo/bar/foobar.bar
+		//   $matches[0][0] is the whole string "/foo/bar/foobar.bar"
+		//
+		//   ^(.+?)
+		//   This gets the file path "/foo/bar/" for $matches[1][0]
+		//
+		//   ([^\/\\\\]+)$
+		//   This gets the file name "foobar.bar" for $matches[2][0]
+		//
+		preg_match_all('/^(.+?)([^\/\\\\]+)$/', $file, $matches );
+		$newName = $matches[2][0];
+		foreach ( $patterns as $key => $pattern ) {
+			//Rename over the patterns
+			$newName = preg_replace( $pattern, $replaceStrs[$key], $newName );
+		}
+		if( $matches[2][0] != $newName ) {
+			if( $test ) {
+				echo "File \"{$matches[2][0]}\" will renamed to \"$newName\"\n";
+			} else {
+				rename ( $file, "{$matches[1][0]}$newName" );
+			}
+			if ( $logfile ) {
+				
+			}
+		}/* else {
+			echo "File \"{$matches[0][0]}\" will not be renamed\n";
+		}
+		//*/
+	}
+	echo "\n";
+}
+if ( $test ) echo "*** Test enabled ***\n\n";
+
+
+
+//------- End Operations -------*/
+?>
\ No newline at end of file