]> git.mjollnir.org Git - scripts.git/commitdiff
added a bunch of new scripts from ~/bin
authorPenny Leach <penny@mjollnir.org>
Sat, 19 Sep 2009 11:27:00 +0000 (13:27 +0200)
committerPenny Leach <penny@mjollnir.org>
Sat, 19 Sep 2009 11:27:00 +0000 (13:27 +0200)
12 files changed:
bin/256colors2.pl [new file with mode: 0644]
bin/dbsize.pl [new file with mode: 0755]
bin/h [new file with mode: 0755]
bin/newfgits [new file with mode: 0755]
bin/obfuscate [new file with mode: 0755]
bin/plshandler [new file with mode: 0755]
bin/repo [new file with mode: 0755]
bin/uc [new file with mode: 0755]
bin/unicode_smileys.pl [new file with mode: 0644]
bin/updategitcache [new file with mode: 0755]
bin/vservershutdown [new file with mode: 0755]
bin/wifi [new file with mode: 0755]

diff --git a/bin/256colors2.pl b/bin/256colors2.pl
new file mode 100644 (file)
index 0000000..0e1292a
--- /dev/null
@@ -0,0 +1,63 @@
+#!/usr/bin/perl
+# Author: Todd Larason <jtl@molehill.org>
+# $XFree86: xc/programs/xterm/vttests/256colors2.pl,v 1.1 1999/07/11 08:49:54 dawes Exp $
+
+# use the resources for colors 0-15 - usually more-or-less a
+# reproduction of the standard ANSI colors, but possibly more
+# pleasing shades
+
+# colors 16-231 are a 6x6x6 color cube
+for ($red = 0; $red < 6; $red++) {
+    for ($green = 0; $green < 6; $green++) {
+       for ($blue = 0; $blue < 6; $blue++) {
+           printf("\x1b]4;%d;rgb:%2.2x/%2.2x/%2.2x\x1b\\",
+                  16 + ($red * 36) + ($green * 6) + $blue,
+                  int ($red * 42.5),
+                  int ($green * 42.5),
+                  int ($blue * 42.5));
+       }
+    }
+}
+
+# colors 232-255 are a grayscale ramp, intentionally leaving out
+# black and white
+for ($gray = 0; $gray < 24; $gray++) {
+    $level = ($gray * 10) + 8;
+    printf("\x1b]4;%d;rgb:%2.2x/%2.2x/%2.2x\x1b\\",
+          232 + $gray, $level, $level, $level);
+}
+
+
+# display the colors
+
+# first the system ones:
+print "System colors:\n";
+for ($color = 0; $color < 8; $color++) {
+    print "\x1b[48;5;${color}m  ";
+}
+print "\x1b[0m\n";
+for ($color = 8; $color < 16; $color++) {
+    print "\x1b[48;5;${color}m  ";
+}
+print "\x1b[0m\n\n";
+
+# now the color cube
+print "Color cube, 6x6x6:\n";
+for ($green = 0; $green < 6; $green++) {
+    for ($red = 0; $red < 6; $red++) {
+       for ($blue = 0; $blue < 6; $blue++) {
+           $color = 16 + ($red * 36) + ($green * 6) + $blue;
+           print "\x1b[48;5;${color}m  ";
+       }
+       print "\x1b[0m ";
+    }
+    print "\n";
+}
+
+
+# now the grayscale ramp
+print "Grayscale ramp:\n";
+for ($color = 232; $color < 256; $color++) {
+    print "\x1b[48;5;${color}m  ";
+}
+print "\x1b[0m\n";
diff --git a/bin/dbsize.pl b/bin/dbsize.pl
new file mode 100755 (executable)
index 0000000..c809007
--- /dev/null
@@ -0,0 +1,55 @@
+#!/usr/bin/perl -w
+
+use strict;
+
+my $version = @ARGV ? $ARGV[0] : "8.3";
+
+my @db  = `/usr/lib/postgresql/$version/bin/oid2name`; # --cluster $version/main`;
+my $basedir;
+if ($version == "7.4") {
+        $basedir = "/var/lib/postgres/data/base";
+}
+else {
+        $basedir = "/var/lib/postgresql/$version/main/base";
+}
+#my @dir = `/usr/bin/du -s -B 1M $basedir/*`; # was -B 1048576, changed to -B 1M for random niceness
+my @dir = `/usr/bin/du -sh $basedir/*`;
+
+my %db;
+my %db_name_size;
+my @db_names;
+
+#Create an assoc array mapping postgres oid numbers to db name:
+foreach my $db (@db) {
+    chomp $db;
+    next if ($db =~ m/^All databases:/ || $db =~ m/^-+$/);
+    if ($version == "7.4") {
+        unless($db =~ m/^(\d+) += (\w+)/) {
+            print "No match for '$db'\n";
+            next;
+        }
+        $db{$1} = $2;
+    }
+    else {
+        unless($db =~ m/^\s+(\d+)\s+(\w+)/) {
+            next;
+        }
+        $db{$1} = $2;
+    }
+}
+
+#Get the size of each subdir which represents a database:
+#(subdirs are named by the db's oid)
+#Associate that size with the name of the db
+foreach my $dir (@dir) {
+    chomp $dir;
+    if ($dir =~ m!^(\d+.*?)\s+/.+/(\d+)$!) {
+        $db_name_size{$db{$2}} = $1;
+    }
+}
+
+#Print db sizes and names, ordered by name of db:
+@db_names = sort(keys(%db_name_size));
+foreach my $db_name (@db_names) {
+    printf("%8s %s\n",$db_name_size{$db_name},$db_name);
+}
diff --git a/bin/h b/bin/h
new file mode 100755 (executable)
index 0000000..8889418
--- /dev/null
+++ b/bin/h
@@ -0,0 +1,19 @@
+#!/usr/bin/perl -X
+
+# perl -nle '/^=item (\w+)/ && print $1' `perldoc -l perlfunc` | grep 'x$'
+
+=comment
+length q values until eof setpriority bind recv
+and print chr oct ord q sort pos
+and print chr ord q y study
+and print chr hex reverse 4672
+and print chr ord reverse q my caller eval m
+and print chr ord ucfirst q symlink for times
+and print uc chr ord scalar reverse q goto delete unshift untie undef log
+and print chr ord uc q push goto sleep
+and print chr length q q truncate q
+and print chr length q time for exit
+=cut
+
+length q values until eof setpriority bind recv and print chr oct ord q sort pos and print chr ord q y study and print chr hex reverse 4672 and print chr ord reverse q my caller eval m  and print chr ord ucfirst q symlink for times and print uc chr ord scalar reverse q goto delete unshift untie undef log and print chr ord uc q push goto sleep and print chr length q q truncate q and print chr length q time for exit
+
diff --git a/bin/newfgits b/bin/newfgits
new file mode 100755 (executable)
index 0000000..620461d
--- /dev/null
@@ -0,0 +1,33 @@
+#!/bin/sh
+
+# run like:
+# newfgits reponame
+# or
+# newfgits reponame private
+
+GITSERVER=git.mjollnir.org
+PUBLICGITPATH=/var/git
+PRIVATEGITPATH=/var/gitprivate
+
+REPO=$1
+PRIVATE=$2
+
+GITPATH=$PUBLICGITPATH
+
+if [ "$PRIVATE" = "private" ]; then
+    GITPATH=$PRIVATEGITPATH
+fi
+
+GIT_DIR=~/.fgits/$REPO.git git init --bare && cd .fgits/$REPO.git \
+    && git config core.bare false && git config core.worktree ../../ \
+    && git remote add origin ssh://$GITSERVER$GITPATH/$REPO.git \
+    && git config branch.master.remote origin && git config branch.master.merge refs/heads/master
+
+ssh $GITSERVER "GIT_DIR=$GITPATH/$REPO.git git init-db"
+
+echo "
+[.fgits/$REPO.git]
+checkout = git_fake_bare_checkout 'ssh://$GITSERVER$GITPATH/$REPO.git' '$REPO.git' '../../'
+" >> ~/.mrconfig
+
+echo "done! now vcsh mr, and issue 'git commit -a && git push"
diff --git a/bin/obfuscate b/bin/obfuscate
new file mode 100755 (executable)
index 0000000..0300416
--- /dev/null
@@ -0,0 +1,21 @@
+#!/usr/bin/env perl
+use strict;
+use warnings;
+use utf8;
+
+my $str = $ARGV[0];
+my $encstr = '';
+
+my $start_char = 0x20;
+my $end_char = 0x7e;
+my $char_range = $end_char - $start_char + 1;
+
+srand(length($str));
+foreach my $c (split(//,$str)) {
+    $c = ord($c) - $start_char;
+    my $pad = int(rand($char_range));
+    $c = (($c + $pad) % ($char_range)) + $start_char;
+    $encstr .= chr($c);
+}
+
+print "perl -e '".'srand(length($s=join("",map {if($_){chr($_)}} split(/(...)/,"'.join('',map { sprintf "%03d",ord($_) } split(//,$encstr) ).'"))));print join("",map {chr(((ord($_)+'.($char_range - $start_char).'-int(rand('.$char_range.')))%'.$char_range.')+'.$start_char.')} split(//,$s))."\n";'."'\n";
diff --git a/bin/plshandler b/bin/plshandler
new file mode 100755 (executable)
index 0000000..3c06c7c
--- /dev/null
@@ -0,0 +1,51 @@
+#!/bin/sh
+#
+# plshandler -- interactive handler for m3u/pls files to be fed to xmms2
+#
+# Copyright © martin f. krafft <madduck@madduck.net>
+# Released under the terms of the Artistic Licence 2.0
+#
+set -eu
+
+gxmessage -buttons '_Replace:103,_Queue:102,_Insert:101,_Play next:100,_Cancel:1' \
+          -default '_Play next' \
+          -nearmouse -name 'Play stream' \
+          "What should I do with the selected tunes?" || ret=$?
+
+add_command=add
+
+case ${ret:-0} in
+  0|1) exit 0;;
+  100) 
+       # Play next, so we just clear the playlist and leave add_command as add
+       # since xmms2 will play the current song to its end and then start from 0
+       xmms2 clear
+       ;;
+  101) 
+       # Insert, this is tricky since we need to find the position to use to insert
+       # and keep incrementing it on every insert, since otherwise the new entries
+       # will end up in reverse order.
+       position="$(xmms2 list | sed -rne 's,^->\[([[:digit:]]+)/.+,\1,p')"
+       if [ -n "$position" ]; then
+               # executed on evaluation.
+               add_command='insert $((position = position+1))'
+       fi
+       ;;
+  102) 
+       # Queue, which is the default behaviour for 'add', so we do nothing
+       :
+       ;;
+  103) 
+       # Replace, more or less like Play next, except we have to stop xmms2 to
+       # also kill the current song
+       xmms2 stop
+       xmms2 clear
+       ;;
+esac
+
+sed -e '/^#/d;s/^File[[:digit:]]*=//' "$@" | \
+       while read url; do
+               eval xmms2 $add_command "'$url'"
+       done
+
+exec xmms2 play
diff --git a/bin/repo b/bin/repo
new file mode 100755 (executable)
index 0000000..ff7c418
--- /dev/null
+++ b/bin/repo
@@ -0,0 +1,596 @@
+#!/bin/sh
+
+## repo default configuration
+##
+REPO_URL='git://android.git.kernel.org/tools/repo.git'
+REPO_REV='stable'
+
+# Copyright (C) 2008 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+magic='--calling-python-from-/bin/sh--'
+"""exec" python -E "$0" "$@" """#$magic"
+if __name__ == '__main__':
+  import sys
+  if sys.argv[-1] == '#%s' % magic:
+    del sys.argv[-1]
+del magic
+
+# increment this whenever we make important changes to this script
+VERSION = (1, 9)
+
+# increment this if the MAINTAINER_KEYS block is modified
+KEYRING_VERSION = (1,0)
+MAINTAINER_KEYS = """
+
+     Repo Maintainer <repo@android.kernel.org>
+-----BEGIN PGP PUBLIC KEY BLOCK-----
+Version: GnuPG v1.4.2.2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mNRQu3Hhxl3hHDVbt5CeJBb26aQcQrFz69W
+zE3GNvmJosh6leayjtI9P2A6iEkEGBECAAkFAkj3uiACGwwACgkQFlMNXpIPXGWp
+TACbBS+Up3RpfYVfd63c1cDdlru13pQAn3NQy/SN858MkxN+zym86UBgOad2
+=CMiZ
+-----END PGP PUBLIC KEY BLOCK-----
+"""
+
+GIT = 'git'                     # our git command
+MIN_GIT_VERSION = (1, 5, 4)     # minimum supported git version
+repodir = '.repo'               # name of repo's private directory
+S_repo = 'repo'                 # special repo reposiory
+S_manifests = 'manifests'       # special manifest repository
+REPO_MAIN = S_repo + '/main.py' # main script
+
+
+import optparse
+import os
+import re
+import readline
+import subprocess
+import sys
+
+home_dot_repo = os.path.expanduser('~/.repoconfig')
+gpg_dir = os.path.join(home_dot_repo, 'gnupg')
+
+extra_args = []
+init_optparse = optparse.OptionParser(usage="repo init -u url [options]")
+
+# Logging
+group = init_optparse.add_option_group('Logging options')
+group.add_option('-q', '--quiet',
+                 dest="quiet", action="store_true", default=False,
+                 help="be quiet")
+
+# Manifest
+group = init_optparse.add_option_group('Manifest options')
+group.add_option('-u', '--manifest-url',
+                 dest='manifest_url',
+                 help='manifest repository location', metavar='URL')
+group.add_option('-o', '--origin',
+                 dest='manifest_origin',
+                 help="use REMOTE instead of 'origin' to track upstream",
+                 metavar='REMOTE')
+group.add_option('-b', '--manifest-branch',
+                 dest='manifest_branch',
+                 help='manifest branch or revision', metavar='REVISION')
+group.add_option('-m', '--manifest-name',
+                 dest='manifest_name',
+                 help='initial manifest file (deprecated)',
+                 metavar='NAME.xml')
+group.add_option('--mirror',
+                 dest='mirror', action='store_true',
+                 help='mirror the forrest')
+
+# Tool
+group = init_optparse.add_option_group('repo Version options')
+group.add_option('--repo-url',
+                 dest='repo_url',
+                 help='repo repository location', metavar='URL')
+group.add_option('--repo-branch',
+                 dest='repo_branch',
+                 help='repo branch or revision', metavar='REVISION')
+group.add_option('--no-repo-verify',
+                 dest='no_repo_verify', action='store_true',
+                 help='do not verify repo source code')
+
+
+class CloneFailure(Exception):
+  """Indicate the remote clone of repo itself failed.
+  """
+
+
+def _Init(args):
+  """Installs repo by cloning it over the network.
+  """
+  opt, args = init_optparse.parse_args(args)
+  if args or not opt.manifest_url:
+    init_optparse.print_usage()
+    sys.exit(1)
+
+  url = opt.repo_url
+  if not url:
+    url = REPO_URL
+    extra_args.append('--repo-url=%s' % url)
+
+  branch = opt.repo_branch
+  if not branch:
+    branch = REPO_REV
+    extra_args.append('--repo-branch=%s' % branch)
+
+  if branch.startswith('refs/heads/'):
+    branch = branch[len('refs/heads/'):]
+  if branch.startswith('refs/'):
+    print >>sys.stderr, "fatal: invalid branch name '%s'" % branch
+    raise CloneFailure()
+
+  if not os.path.isdir(repodir):
+    try:
+      os.mkdir(repodir)
+    except OSError, e:
+      print >>sys.stderr, \
+            'fatal: cannot make %s directory: %s' % (
+            repodir, e.strerror)
+      # Don't faise CloneFailure; that would delete the
+      # name. Instead exit immediately.
+      #
+      sys.exit(1)
+
+  _CheckGitVersion()
+  try:
+    if _NeedSetupGnuPG():
+      can_verify = _SetupGnuPG(opt.quiet)
+    else:
+      can_verify = True
+
+    if not opt.quiet:
+      print >>sys.stderr, 'Getting repo ...'
+      print >>sys.stderr, '   from %s' % url
+
+    dst = os.path.abspath(os.path.join(repodir, S_repo))
+    _Clone(url, dst, opt.quiet)
+
+    if can_verify and not opt.no_repo_verify:
+      rev = _Verify(dst, branch, opt.quiet)
+    else:
+      rev = 'refs/remotes/origin/%s^0' % branch
+
+    _Checkout(dst, branch, rev, opt.quiet)
+  except CloneFailure:
+    if opt.quiet:
+      print >>sys.stderr, \
+        'fatal: repo init failed; run without --quiet to see why'
+    raise
+
+
+def _CheckGitVersion():
+  cmd = [GIT, '--version']
+  proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+  ver_str = proc.stdout.read().strip()
+  proc.stdout.close()
+  proc.wait()
+
+  if not ver_str.startswith('git version '):
+    print >>sys.stderr, 'error: "%s" unsupported' % ver_str
+    raise CloneFailure()
+
+  ver_str = ver_str[len('git version '):].strip()
+  ver_act = tuple(map(lambda x: int(x), ver_str.split('.')[0:3]))
+  if ver_act < MIN_GIT_VERSION:
+    need = '.'.join(map(lambda x: str(x), MIN_GIT_VERSION))
+    print >>sys.stderr, 'fatal: git %s or later required' % need
+    raise CloneFailure()
+
+
+def _NeedSetupGnuPG():
+  if not os.path.isdir(home_dot_repo):
+    return True
+
+  kv = os.path.join(home_dot_repo, 'keyring-version')
+  if not os.path.exists(kv):
+    return True
+
+  kv = open(kv).read()
+  if not kv:
+    return True
+
+  kv = tuple(map(lambda x: int(x), kv.split('.')))
+  if kv < KEYRING_VERSION:
+    return True
+  return False
+
+
+def _SetupGnuPG(quiet):
+  if not os.path.isdir(home_dot_repo):
+    try:
+      os.mkdir(home_dot_repo)
+    except OSError, e:
+      print >>sys.stderr, \
+            'fatal: cannot make %s directory: %s' % (
+            home_dot_repo, e.strerror)
+      sys.exit(1)
+
+  if not os.path.isdir(gpg_dir):
+    try:
+      os.mkdir(gpg_dir, 0700)
+    except OSError, e:
+      print >>sys.stderr, \
+            'fatal: cannot make %s directory: %s' % (
+            gpg_dir, e.strerror)
+      sys.exit(1)
+
+  env = dict(os.environ)
+  env['GNUPGHOME'] = gpg_dir
+
+  cmd = ['gpg', '--import']
+  try:
+    proc = subprocess.Popen(cmd,
+                            env = env,
+                            stdin = subprocess.PIPE)
+  except OSError, e:
+    if not quiet:
+      print >>sys.stderr, 'warning: gpg (GnuPG) is not available.'
+      print >>sys.stderr, 'warning: Installing it is strongly encouraged.'
+      print >>sys.stderr
+    return False
+
+  proc.stdin.write(MAINTAINER_KEYS)
+  proc.stdin.close()
+
+  if proc.wait() != 0:
+    print >>sys.stderr, 'fatal: registering repo maintainer keys failed'
+    sys.exit(1)
+  print
+
+  fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
+  fd.write('.'.join(map(lambda x: str(x), KEYRING_VERSION)) + '\n')
+  fd.close()
+  return True
+
+
+def _SetConfig(local, name, value):
+  """Set a git configuration option to the specified value.
+  """
+  cmd = [GIT, 'config', name, value]
+  if subprocess.Popen(cmd, cwd = local).wait() != 0:
+    raise CloneFailure()
+
+
+def _Fetch(local, quiet, *args):
+  cmd = [GIT, 'fetch']
+  if quiet:
+    cmd.append('--quiet')
+    err = subprocess.PIPE
+  else:
+    err = None
+  cmd.extend(args)
+  cmd.append('origin')
+
+  proc = subprocess.Popen(cmd, cwd = local, stderr = err)
+  if err:
+    proc.stderr.read()
+    proc.stderr.close()
+  if proc.wait() != 0:
+    raise CloneFailure()
+
+
+def _Clone(url, local, quiet):
+  """Clones a git repository to a new subdirectory of repodir
+  """
+  try:
+    os.mkdir(local)
+  except OSError, e:
+    print >>sys.stderr, \
+          'fatal: cannot make %s directory: %s' \
+          % (local, e.strerror)
+    raise CloneFailure()
+
+  cmd = [GIT, 'init', '--quiet']
+  try:
+    proc = subprocess.Popen(cmd, cwd = local)
+  except OSError, e:
+    print >>sys.stderr
+    print >>sys.stderr, "fatal: '%s' is not available" % GIT
+    print >>sys.stderr, 'fatal: %s' % e
+    print >>sys.stderr
+    print >>sys.stderr, 'Please make sure %s is installed'\
+                        ' and in your path.' % GIT
+    raise CloneFailure()
+  if proc.wait() != 0:
+    print >>sys.stderr, 'fatal: could not create %s' % local
+    raise CloneFailure()
+
+  _SetConfig(local, 'remote.origin.url', url)
+  _SetConfig(local, 'remote.origin.fetch',
+                    '+refs/heads/*:refs/remotes/origin/*')
+  _Fetch(local, quiet)
+  _Fetch(local, quiet, '--tags')
+
+
+def _Verify(cwd, branch, quiet):
+  """Verify the branch has been signed by a tag.
+  """
+  cmd = [GIT, 'describe', 'origin/%s' % branch]
+  proc = subprocess.Popen(cmd,
+                          stdout=subprocess.PIPE,
+                          stderr=subprocess.PIPE,
+                          cwd = cwd)
+  cur = proc.stdout.read().strip()
+  proc.stdout.close()
+
+  proc.stderr.read()
+  proc.stderr.close()
+
+  if proc.wait() != 0 or not cur:
+    print >>sys.stderr
+    print >>sys.stderr,\
+      "fatal: branch '%s' has not been signed" \
+      % branch
+    raise CloneFailure()
+
+  m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
+  if m:
+    cur = m.group(1)
+    if not quiet:
+      print >>sys.stderr
+      print >>sys.stderr, \
+        "info: Ignoring branch '%s'; using tagged release '%s'" \
+        % (branch, cur)
+      print >>sys.stderr
+
+  env = dict(os.environ)
+  env['GNUPGHOME'] = gpg_dir
+
+  cmd = [GIT, 'tag', '-v', cur]
+  proc = subprocess.Popen(cmd,
+                          stdout = subprocess.PIPE,
+                          stderr = subprocess.PIPE,
+                          cwd = cwd,
+                          env = env)
+  out = proc.stdout.read()
+  proc.stdout.close()
+
+  err = proc.stderr.read()
+  proc.stderr.close()
+
+  if proc.wait() != 0:
+    print >>sys.stderr
+    print >>sys.stderr, out
+    print >>sys.stderr, err
+    print >>sys.stderr
+    raise CloneFailure()
+  return '%s^0' % cur
+
+
+def _Checkout(cwd, branch, rev, quiet):
+  """Checkout an upstream branch into the repository and track it.
+  """
+  cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
+  if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
+    raise CloneFailure()
+
+  _SetConfig(cwd, 'branch.default.remote', 'origin')
+  _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)
+
+  cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
+  if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
+    raise CloneFailure()
+
+  cmd = [GIT, 'read-tree', '--reset', '-u']
+  if not quiet:
+    cmd.append('-v')
+  cmd.append('HEAD')
+  if subprocess.Popen(cmd, cwd = cwd).wait() != 0:
+    raise CloneFailure()
+
+
+def _FindRepo():
+  """Look for a repo installation, starting at the current directory.
+  """
+  dir = os.getcwd()
+  repo = None
+
+  while dir != '/' and not repo:
+    repo = os.path.join(dir, repodir, REPO_MAIN)
+    if not os.path.isfile(repo):
+      repo = None
+      dir = os.path.dirname(dir)
+  return (repo, os.path.join(dir, repodir))
+
+
+class _Options:
+  help = False
+
+
+def _ParseArguments(args):
+  cmd = None
+  opt = _Options()
+  arg = []
+
+  for i in xrange(0, len(args)):
+    a = args[i]
+    if a == '-h' or a == '--help':
+      opt.help = True
+
+    elif not a.startswith('-'):
+      cmd = a
+      arg = args[i + 1:]
+      break
+  return cmd, opt, arg
+
+
+def _Usage():
+  print >>sys.stderr,\
+"""usage: repo COMMAND [ARGS]
+
+repo is not yet installed.  Use "repo init" to install it here.
+
+The most commonly used repo commands are:
+
+  init      Install repo in the current working directory
+  help      Display detailed help on a command
+
+For access to the full online help, install repo ("repo init").
+"""
+  sys.exit(1)
+
+
+def _Help(args):
+  if args:
+    if args[0] == 'init':
+      init_optparse.print_help()
+    else:
+      print >>sys.stderr,\
+      "error: '%s' is not a bootstrap command.\n"\
+      '        For access to online help, install repo ("repo init").'\
+      % args[0]
+  else:
+    _Usage()
+  sys.exit(1)
+
+
+def _NotInstalled():
+  print >>sys.stderr,\
+'error: repo is not installed.  Use "repo init" to install it here.'
+  sys.exit(1)
+
+
+def _NoCommands(cmd):
+  print >>sys.stderr,\
+"""error: command '%s' requires repo to be installed first.
+       Use "repo init" to install it here.""" % cmd
+  sys.exit(1)
+
+
+def _RunSelf(wrapper_path):
+  my_dir = os.path.dirname(wrapper_path)
+  my_main = os.path.join(my_dir, 'main.py')
+  my_git = os.path.join(my_dir, '.git')
+
+  if os.path.isfile(my_main) and os.path.isdir(my_git):
+    for name in ['git_config.py',
+                 'project.py',
+                 'subcmds']:
+      if not os.path.exists(os.path.join(my_dir, name)):
+        return None, None
+    return my_main, my_git
+  return None, None
+
+
+def _SetDefaultsTo(gitdir):
+  global REPO_URL
+  global REPO_REV
+
+  REPO_URL = gitdir
+  proc = subprocess.Popen([GIT,
+                           '--git-dir=%s' % gitdir,
+                           'symbolic-ref',
+                           'HEAD'],
+                          stdout = subprocess.PIPE,
+                          stderr = subprocess.PIPE)
+  REPO_REV = proc.stdout.read().strip()
+  proc.stdout.close()
+
+  proc.stderr.read()
+  proc.stderr.close()
+
+  if proc.wait() != 0:
+    print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
+    sys.exit(1)
+
+
+def main(orig_args):
+  main, dir = _FindRepo()
+  cmd, opt, args = _ParseArguments(orig_args)
+
+  wrapper_path = os.path.abspath(__file__)
+  my_main, my_git = _RunSelf(wrapper_path)
+
+  if not main:
+    if opt.help:
+      _Usage()
+    if cmd == 'help':
+      _Help(args)
+    if not cmd:
+      _NotInstalled()
+    if cmd == 'init':
+      if my_git:
+        _SetDefaultsTo(my_git)
+      try:
+        _Init(args)
+      except CloneFailure:
+        for root, dirs, files in os.walk(repodir, topdown=False):
+          for name in files:
+            os.remove(os.path.join(root, name))
+          for name in dirs:
+            os.rmdir(os.path.join(root, name))
+        os.rmdir(repodir)
+        sys.exit(1)
+      main, dir = _FindRepo()
+    else:
+      _NoCommands(cmd)
+
+  if my_main:
+    main = my_main
+
+  ver_str = '.'.join(map(lambda x: str(x), VERSION))
+  me = [main,
+        '--repo-dir=%s' % dir,
+        '--wrapper-version=%s' % ver_str,
+        '--wrapper-path=%s' % wrapper_path,
+        '--']
+  me.extend(orig_args)
+  me.extend(extra_args)
+  try:
+    os.execv(main, me)
+  except OSError, e:
+    print >>sys.stderr, "fatal: unable to start %s" % main
+    print >>sys.stderr, "fatal: %s" % e
+    sys.exit(148)
+
+
+if __name__ == '__main__':
+  main(sys.argv[1:])
+
diff --git a/bin/uc b/bin/uc
new file mode 100755 (executable)
index 0000000..a5137ce
--- /dev/null
+++ b/bin/uc
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+unicode --max=0 --colour=off "$@" | sensible-pager
diff --git a/bin/unicode_smileys.pl b/bin/unicode_smileys.pl
new file mode 100644 (file)
index 0000000..1b8d5ea
--- /dev/null
@@ -0,0 +1,138 @@
+## unicode_smileys.pl
+## (C) 2008 Mathieu Petit-Clair <scyrmaa@eml.cc>
+##
+## Released under the GPLv2.
+##
+## ChangeLog:
+## 0.3 -- Using the proper signal to filter inbound messages (fixes theme issues)
+## 0.2 -- Added some more smileys, using the full charname.
+## 0.1 -- Initial version.
+##
+## Known bugs (as of 0.3): 
+##  * Outgoing messages are not encoded. 
+##
+## Caveat: 
+##  * Obviously, you need a font that can display the unicode characters to see anything...
+##
+
+use Irssi qw();
+use strict;
+use vars qw($VERSION %IRSSI);
+use charnames ':full';
+
+$VERSION = "0.3";
+
+%IRSSI = (
+         'authors'     => 'Mathieu Petit-Clair',
+         'contact'     => 'scyrmaa\@eml.cc',
+         'name'        => 'Unicode smiley filter',
+         'description' => 'Filters smiley-strings - :-), :-(, (h), (star), etc. - to display as unicode characters, where available. Need help assigning the "proper" characters for a lot of missing smileys, please send in those you find!',
+         'license'     => 'GPL',
+         'url'         => 'none for now.',
+         'changed'     => '2008-08-15'
+        );
+
+## this should be dynamic, let people choose a specific set, etc.
+## this first set is based on Sk*p*.
+my %smileys = ( 
+  "(star)" => "\N{BLACK STAR}", # or white, could have a theme ... 
+  "(*)" => "\N{BLACK STAR}", 
+  "(love)" => "\N{HEAVY BLACK HEART}",
+  "(h)" => "\N{HEAVY BLACK HEART}",
+  "(heart)" => "\N{HEAVY BLACK HEART}",
+  "(moon)" => "\N{FIRST QUARTER MOON}", # or last
+  "(music)" => "\N{BEAMED EIGHTH NOTES}",
+  "(sun)" => "\N{BLACK SUN WITH RAYS}", # or white
+  ":-)" => "\N{BLACK SMILING FACE}",
+  ":)" => "\N{BLACK SMILING FACE}", # or white
+  ":-D" => "\N{BLACK SMILING FACE}",
+  ":D" => "\N{BLACK SMILING FACE}",
+  ":(" => "\N{WHITE FROWNING FACE}", # There's no black frowning face in unicode, apparently.
+  ":-(" => "\N{WHITE FROWNING FACE}",
+  "(y)" => "\N{HEAVY CHECK MARK}", # yes
+  "(n)" => "\N{HEAVY MULTIPLICATION X}", # no
+  "(e)" => "\N{ENVELOPE}", #mail
+  "(cash)" => "\N{FULLWIDTH DOLLAR SIGN}",
+  "(o)" => "\N{HOURGLASS}", # clock/time
+  "(rain)" => "\N{UMBRELLA WITH RAIN DROPS}", 
+  "(mp)" => "\N{BLACK TELEPHONE}", 
+  "(F)" => "\N{FLOWER}",
+  "(pizza)" => "\N{CIRCLED ASTERISK OPERATOR}", # not sure I would eat this pizza.
+  ## smileys that have yet to be found - there's a lot of the basic skype smileys that I don't care about. 
+  #"8-)" => "", # cool
+  #":O" => "", # surprised
+  #";)" => "", 
+  #";(" => "", # crying
+  #"(ninja)" => "",
+  #"(puke)" => "", 
+  #"(bow)" => "",
+  #"(coffee)" => "", # can you believe that this is not in unicode!?
+  #"(beer)" => "", # I'm *sure* some CJK character can be used for this
+  #"(drink)" => "", 
+  #"(devil)" => "",
+  #"(u)" => "", # broken heart
+);
+
+
+sub smileify {
+       my $msg = $_[0];
+       my $smileify = 0;
+
+       foreach (keys %smileys)
+       {
+           if($smileys{$_} && $msg =~ /[.^:]?:\Q$_/)
+        {
+            $smileify = $smileys{$_};
+               $msg =~ s/$1/$smileify/e;
+        }
+       }
+       
+       return $msg;
+}
+
+#sub sig_smiley {
+       #my ($server, $msg, $nick, $address, $target) = @_;
+    #my $msg = @_[0];
+       #$target = $nick if $target eq "";
+       #$nick = $server->{'nick'} if $address eq "";
+       #my $newmsg = smileify(@_[0]);
+
+       #if ($newmsg ne $msg) 
+       #{
+           #$server->window_item_find ($target)->print ("<$nick> " . $newmsg, MSGLEVEL_PUBLIC);
+        #Irssi::signal_stop();
+       #}
+    #return $newmsg;
+#}
+
+sub sig_smiley_inbound {
+    my ($server, $msg, $nick, $address, $target) = @_;
+    my $newmsg = smileify($msg);
+    if ($newmsg ne $msg) {
+        Irssi::signal_emit('event privmsg', ($server, $newmsg, $nick, $address, $target));
+        Irssi::signal_stop();
+    }
+}
+
+sub sig_smiley_outbound {
+    my ($data, $server, $witem) = @_;
+    
+    return unless (defined($server) && $server && $server->{connected});
+    return unless (defined($witem) && $witem &&
+            ($witem->{type} eq 'CHANNEL' || $witem->{type} eq 'QUERY'));
+
+    my $newmsg = smileify($data);
+    if ($newmsg ne $data) {
+        Irssi::signal_emit('event send text', ($newmsg, $server, $witem));
+        Irssi::signal_stop();
+    }
+}
+
+#Irssi::signal_add('message own_public', 'sig_smiley_own_public');
+#Irssi::signal_add('message public', 'sig_smiley');
+#Irssi::signal_add('message own_private', 'sig_smiley');
+#Irssi::signal_add('message private', 'sig_smiley');
+
+Irssi::signal_add_first('event privmsg', 'sig_smiley_inbound');
+#Irssi::signal_add_last('event send text', 'sig_smiley_outbound');
+
diff --git a/bin/updategitcache b/bin/updategitcache
new file mode 100755 (executable)
index 0000000..9262f1d
--- /dev/null
@@ -0,0 +1,6 @@
+#!/bin/sh
+
+echo 'updating moodle' && cd /home/penny/cache/git/moodle/public && git fetch origin
+echo 'updaing mahara' && cd /home/penny/cache/git/mahara/public && git fetch origin
+echo 'done'
+
diff --git a/bin/vservershutdown b/bin/vservershutdown
new file mode 100755 (executable)
index 0000000..88a7f7f
--- /dev/null
@@ -0,0 +1,5 @@
+#!/bin/bash
+
+for i in $(sudo vserver-stat | awk ' { print $8 }' | grep -v NAME );
+    do sudo vserver $i stop;
+done
diff --git a/bin/wifi b/bin/wifi
new file mode 100755 (executable)
index 0000000..49786ec
--- /dev/null
+++ b/bin/wifi
@@ -0,0 +1,7 @@
+#!/bin/bash
+
+sudo killall dhclient
+sudo ifdown wlan0
+sudo ifdown eth0
+sudo ifup wlan0=wifi-$1
+