Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
11 total  XML / RSS feed 

script for migrating from UW-IMAP to Dovecot [PATCHED]

#!/bin/bash

# A script for migrating from UW-IMAP to Dovecot
#
# By Andrew Ziem
# Copyright (c) 2007 Springs Rescue Mission.  All rights reserved.
#
#
# Moves UW-IMAP mboxes from two locations to ~/mail so that Dovecot
# can easily convert mboxes to Maildirs.  Mailboxes with whitespace
# should be handled properly, and IMAP subscriptions should be preserved.
#
#


# Edit the below variables

#HOME_USERS=/home
HOME_USERS=/home/users

#MAIL_SPOOL=/var/mail
MAIL_SPOOL=/var/spool/mail



# to this function pass the user name
function move_mailboxlist
{
        if [ ! -d "$HOME_USERS/$1" ];
        then
                echo "Error: $HOME_USERS/$1 does not exist"
                return 0
        fi

        # make ~/mail
        cd "$HOME_USERS/$1"
        mkdir mail
        chown "$1" mail

        # find each mbox and move it to ~/mail
        if [ ! -f ".mailboxlist" ];
        then
                echo "Warning: .mailboxlist does not exist for $1"
                return 0
        fi
        
        # cat .mailboxlist | while read line; do mv "${line}" ./mail/; done
        cat .mailboxlist | tr '\n' '\0' | xargs -0 mv -t ./mail/

        # preserve subscriptions (to prevent manual resubscriptions)
        mkdir Maildir
        chown "$1" Maildir
        cp -a .mailboxlist Maildir/subscriptions
}

# move inbox from $MAIL_SPOOL to ~/mail/inbox
function move_inbox
{
        if [ ! -f "${MAIL_SPOOL}/$1" ];
        then
                echo "Error: ${MAIL_SPOOL}/$1 does not exist"
                return 0
        fi
        cp "${MAIL_SPOOL}/$1" "${HOME_USERS}/$1/mail/inbox"
        chown "$1" "${HOME_USERS}/$1/mail/inbox"
}

if [ $# -eq 0 ];
then
        echo "First, did you edit the directory names in the script?"
        echo "Then, if you want to do a dry run, prefix mv and cp with echo."
        echo "Then, invoke $0 by passing one or more user names."
        exit
fi

for user in $@
do
        echo "*** Processing user $user"
        move_mailboxlist $user
        move_inbox $user
done

Notifications from shell scripts with CocoaDialog


cd ~/Desktop
curl -L -O http://prdownloads.sourceforge.net/cocoadialog/CocoaDialog-2.1.1.dmg
hdiutil mount CocoaDialog-2.1.1.dmg
sudo mkdir -p /usr/local/bin
sudo ditto -rsrc /Volumes/CocoaDialog/CocoaDialog.app /usr/local/bin/CocoaDialog.app
sudo chown -R root:wheel /usr/local/bin/CocoaDialog.app
sudo chmod -R 0755 /usr/local/bin/CocoaDialog.app
hdiutil unmount /Volumes/CocoaDialog


alias cocoadialog=/usr/local/bin/CocoaDialog.app/Contents/MacOS/CocoaDialog

# cf. http://cocoadialog.sourceforge.net/examples/bubble.sh.txt
cocoadialog bubble --no-timeout --x-placement center --y-placement center --background-top "FF0000" --background-bottom "FF0066"  \
                   --icon-file /usr/local/bin/CocoaDialog.app/Contents/Resources/info.icns --title "News" --text ''



Further information:

- CocoaDialog Documentation
- CocoaDialog Examples
- growlnotify
- Pashua
- man automator

backup files

// create backup copy

#!/bin/bash

filename=$1
date=`date +%Y%m%d`

usage () {
        echo "Usage: `basename $0` filename"
}

if [ -z "$filename" -a ! -f "$filename" ]; then
        usage
        exit 1
fi

rev=0
backup="$filename.$date.$rev"

while [ -f $backup ]; do
        let rev+=1
        backup="$filename.$date.$rev"
done

cp $filename $backup
exit $?

Ruby: Submit Apple Shake Scripts for Batch Render

A quick-n-dirty Ruby script that takes all the Shake scripts in a given folder, checks to make sure they are all set on maximum quality e.g "Base" and then submits them for render.

#! /usr/bin/env ruby

require 'pp'

class Fixnum

def pad(n)
  
  x = self.to_s

  if x.length < n
    pad = "0"*(n - x.length)
    x.insert(0,pad)
  else
    x
  end

end

end

def render(filepath,last_frame)

IO.popen("shake -v xml -exec #{filepath} -t 1-#{last_frame}x1", 'r+')

end

def get_last_frame(file_path)
  
  last_frame = File.open(file_path).grep(/SetTimeRange/).to_s.scan(/\d{2,6}/).first.to_i

end

def get_output_file(file_path)

  out_file = File.open(file_path).grep(/FileOut/).first.gsub(/\"/,"").split(",")[1].lstrip

end

def get_quality(file_path)

  quality = File.open(file_path).grep(/SetUseProxy/).first.match(/\".+\"/).to_a.first

end

# Get location of scripts

$renderQ = {}

puts "Where are the scripts?"
$TARGET = gets.rstrip
$TARGET << "/" if $TARGET !~ /\/$/

$script_list = %x| ls #{$TARGET}*.shk |.split("\n")   # Only files with *.shk extension

# Replace whitespace (if present) in filenames with underscores

$script_list.map! do |f|
    new_name = f.gsub(/\s/,'_')
    unless f == new_name
      puts "Renaming #{f} --> #{new_name}"
      File.rename(f,new_name)
    end
  new_name
end

# Make sure all renders are full-resolution

$script_list.each do |f|

  file,path,filename = File.open(f), File.dirname(f), File.basename(f).split(/\./)

  unless file.read.grep(/SetUseProxy/).first =~ /Base/
    
    new_file = File.open(f).read.gsub!(/^SetUseProxy.+;$/,'SetUseProxy("Base");')
    
    File.open(f,'w') { |f| f.puts new_file }

  end

end

# Get render info on scripts

$script_list.each do |f|
  outfile = get_output_file(f)
  last_frame = get_last_frame(f)
  quality = get_quality(f)
  $renderQ[f] = [last_frame,quality,outfile]
end

# Print report

puts "\n---------| RENDER SCRIPT -- FRAME COUNT -- OUTPUT FILE |---------\n"

$renderQ.sort.each { |k,v| puts "#{k} -- #{v.first} --> #{v.last} | #{v[1]}" }

puts "---------------------------------------------------"

puts "\nPress Enter to continue with render, or force exit."

gets

# Render

$renderQ.each { |k,v| render(k,v.first) }

Cache a local copy of Google Analytics' urchin.js

Speed up your website by caching Google's urchin.js locally, and then refreshing it @nightly with this here script. Some background: http://tramchase.com/blog/broken-urchintracker-calls-google-analytics-down

#!/bin/sh
# urchin.js local caching by Jamie Wilkinson 

# config
DIR=/directory/where/you/want/js

# work
URCHIN=$DIR/urchin.js
wget http://www.google-analytics.com/urchin.js -O $URCHIN.tmp
if [ -s $URCHIN.tmp ]; then
        rm $URCHIN
        mv $URCHIN.tmp $URCHIN
        chmod 644 $URCHIN
fi

exit 0;

tracd debian init script

tracd init script on debian stable. consists of two parts, /etc/init.d/tracd and /etc/default/tracd

This is /etc/init.d/tracd

#! /bin/sh
#
# tracd           Trac standalone server daemon
#
# Author: cocoaberry
#

set -e

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Trac standalone server"
NAME=tracd
DAEMON=/usr/bin/$NAME
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

# defaults for tracd
TRACD_PORT=8080
TRACD_BIND_ADDRESS=0.0.0.0
TRACD_EXTRA_OPTS=

# Read config file if it is present.
if [ -r /etc/default/$NAME ]
then
        . /etc/default/$NAME
fi

#
# Function that starts the daemon/service.
#
d_start() {
        start-stop-daemon --start --background --make-pidfile --quiet \
                --pidfile $PIDFILE --chuid $TRACD_USER \
                --exec $DAEMON -- $TRACD_EXTRA_OPTS --port $TRACD_PORT --hostname $TRACD_BIND_ADDRESS $TRACD_ENVIRONMENTS
}

#
# Function that stops the daemon/service.
#
d_stop() {
        start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE \
                --name $NAME
}

case "$1" in
  start)
        echo -n "Starting $DESC: $NAME"
        d_start
        echo "."
        ;;
  stop)
        echo -n "Stopping $DESC: $NAME"
        d_stop
        echo "."
        ;;
  restart|force-reload)
        #
        # If the "reload" option is implemented, move the "force-reload"
        # option to the "reload" entry above. If not, "force-reload" is
        # just the same as "restart".
        #
        echo -n "Restarting $DESC: $NAME"
        d_stop
        sleep 1
        d_start
        echo "."
        ;;
  *)
        echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0



This is /etc/default/tracd

# Default settings for tracd. This file is sourced by
# /etc/init.d/tracd

# MAJOR HACK - disable globbing so $TRACD_EXTRA_OPTS on cmdline won't expand
# the *
set -f
# The user that tracd runs as
TRACD_USER=tracd
# The environments that tracd manages. If more than one, separate
# with spaces
TRACD_ENVIRONMENTS=/home/tracd/trac-env
# Extra options to tracd
TRACD_EXTRA_OPTS="--auth *,/home/tracd/trac.htdigest,TracRealm"
# The port that tracd binds to. The default is 8080
# TRACD_PORT=8080
# The addresses that tracd binds to. The default is 0.0.0.0
# TRACD_BIND_ADDRESS=0.0.0.0

Shell keepalive script (zsh)

Disclaimer: I do not use this script on TextDrive, due to resource consumption concerns, and would not recommend anyone else doing so without express permission from TPTB.

#!/usr/bin/env zsh

# keepalive
# 
# This is keepalive, a simple zsh script (may be hackable to work for other
# shells) for keeping things running.
# 
# Usage:
# $ keepalive  [command args]
# $ keepalive ssh -N -L 8080:127.0.0.1:8080
# 
# The next three variables can be edited to adjust the action of the script

# If the command dies ${threshold} times in succession without living more
# than ${min_runtime} seconds the script will quit.
local threshold=5
local min_runtime=60

# The script will sleep ${init_sleep_time} seconds after the first failure,
# ${init_sleep_time}*2 after the second, ${init_sleep_time}*4 times after the 
# third, and so on.
local init_sleep_time=5

# ########################### #
# No need to edit below here. #
# ########################### #
local time_started time_ended 
local sleep_time=${init_sleep_time}
local times_until_fail=${threshold}

until (( times_until_fail <= 0 )); do
  time_started=$(date +%s)
  $*
  time_ended=$(date +%s)

  # reset if it's lived longer than ${min_runtime}
  if (( (${time_ended} - ${time_started}) > ${min_runtime} )); then
    times_until_fail=${threshold}
    sleep_time=${init_sleep_time}
  fi

  (( times_until_fail -= 1 ))
 
  echo
  echo "-- $(date +"%d/%m/%y %H:%M:%S"): \`$*\` died!"
  if (( times_until_fail >= 1 )); then
    echo "-- ${times_until_fail} more executions lasting less than ${min_runtime} seconds will result in job failure."
    echo "-- Sleeping ${sleep_time} seconds..."
    echo
    sleep ${sleep_time}
  fi
  
  (( sleep_time *= 2 ))
done

echo "-- Died too many times in too short a space of time. Exiting!"

Copy files matching a regular expression to a new name

// copy similar files to a new name given a regular expression in ruby

for i in `ls *_1.png`; do echo $i; cp $i `echo $i|ruby -pe '$_.sub!(/_1/, "_0")'`; done

Bash script to perform initial import of a rails project

This is still a work in progress. The objective is to script the entire initial svn hassle that needs to be done with a rails project. The first import, then the first checkout, and then dealing with all the files that need to be ignored. Based heavily on:

http://wiki.rubyonrails.org/rails/pages/HowtoUseRailsWithSubversion

In the future I may add capistrano setup and such.

This worked the last time I tried it, but I don't expect it to work the next time.

#!/bin/bash
set -v                         # verbose output

## USAGE: configure the following variables, and execute in your rails root, ie the directory with
## config/ and app/
## NOTE: This script assumes that your directory of your rails root has the same name as both your 
## application, and your svn repo.
##
## This script also assumes that it's ok to make a backup in the parent directory of your
## rails root.

username="jonshea"               # CHANGE ME!!!!!!!
svn_url="http://jonshea.com/svn/" # CHANGE ME!!!!!

## This is still a work in progress. The objective is to script the entire initial svn hassle that 
## needs to be done with a rails project. The first import, then the first checkout, and then 
## dealing with all the files that need to be ignored. Based heavily on: 
##
## http://wiki.rubyonrails.org/rails/pages/HowtoUseRailsWithSubversion
##
## It designed only for freshly created applications, that haven't really be changed at all from the
## original generation script

app_dir=`pwd`
app_name=`basename $app_dir`
svn_url_to_your_repository=${svn_url}${app_name} # Assumes your repo has the same name as your app
echo $app_name
echo $svn_url_to_your_repository

## Do the initial import
svn import . ${svn_url_to_your_repository}/trunk -m "First Import" --username $username



cd ..                           # Back out a directory from the root

## We're going to make a backup of your app. If one is already there, then remove it.
test -d ./pre_svn_backup_$app_name || rm -rf pre_svn_backup_$app_name
mkdir ../pre_svn_backup_$app_name
mv -f $app_dir ./pre_svn_backup_${app_name} # Move the rails app to the backup dir.

mkdir $app_dir # recreate the application directory
cd $app_dir
svn checkout ${svn_url_to_your_repository}/trunk . # Check out the subversion repo to the app directory

## This section cleans up the svn repo, so that you're not versioning things that shouldn't be versioned.
svn remove log/*
svn commit -m 'removing all log files from subversion'
svn propset svn:ignore "*.log" log/
svn update log/
svn commit -m 'Ignoring all files in /log/ ending in .log'

svn remove tmp/
svn commit -m 'removing the temp directory from subversion'
svn propset svn:ignore "*" tmp/
svn update tmp/
svn commit -m 'Ignore the whole tmp/ directory, might not work on subdirectories?'

svn move config/database.yml config/database.example
svn commit -m 'Moving database.yml to database.example to provide a template for anyone who checks out the code'
svn propset svn:ignore "database.yml" config/
svn update config/
svn commit -m 'Ignoring database.yml'

svn move public/dispatch.rb public/dispatch.rb.example
cp public/dispatch.rb.example public/dispatch.rb
svn move public/dispatch.cgi public/dispatch.cgi.example
cp public/dispatch.cgi.example public/dispatch.cgi
svn move public/dispatch.fcgi public/dispatch.fcgi.example
cp public/dispatch.fcgi.example public/dispatch.fcgi
svn commit -m 'Moving dispatch.(star) to dispatch.(star).example to provide a template.'

svn propedit svn:ignore public/ dispatch.rb
svn propedit svn:ignore public/ dispatch.cgi
svn propedit svn:ignore public/ dispatch.fcgi
svn update public/
svn commit -m 'Ignoring dispatch.* files'

svn propedit svn:ignore db/ *.sqlite
svn propedit svn:ignore db/ *.sqlite3
svn commit -m 'Ignore database files'




#cap --apply-to $app_dir $app_name
#svn add config/deploy.rb     
#svn add lib/tasks/capistrano.rake

exit 0

Bash script to export ssh public key to a remote server

This isn't a brilliant script, but it sure can be a time saver. When I add a public key by hand I end up doing a lot more commands.

#!/bin/bash

## USAGE: add_to_server.sh remote_server

## This script will add your ssh dsa public key to remote_server's authorized_keys list, 
## assuming that everything is in it's default location

set -v                                 # verbose output
username="USERNAME"              # CHANGE ME!!!!
remote_server=$1              # assigns the first commandline argument to $remote_server


## Pipe the public key to ssh, then remotely touch the file to make sure it will be there, and concat to the end of it.
## Might work without the touch?
cat ~/.ssh/id_dsa.pub | ssh ${username}@${remote_server} "touch ~/.ssh/authorized_keys && cat - >> ~/.ssh/authorized_keys"

exit 0

World clock shell script

#!/bin/sh
TZ=US/Pacific date +"Jason/Nate: %I:%M %p %a %D"
TZ=US/Central date +"Ryan: %I:%M %p %a %D"
TZ=US/Eastern date +"Jan/Daniel: %I:%M %p %a %D"
TZ=US/Eastern date +"Terrel/Christopher: %I:%M %p %a %D"
TZ=UTC date +"UTC/GMT: %I:%M %p %a %D"
TZ=Europe/Amsterdam date +"Filip/Marten: %I:%M %p %a %D"
TZ=Europe/Amsterdam date +"Florian/Johan: %I:%M %p %a %D"
TZ=Europe/Paris date +"Dean/Damelon: %I:%M %p %a %D"
TZ=Australia/Melbourne date +"Justin: %I:%M %p %a %D"
TZ=NZ date +"Koz: %I:%M %p %a %D"
« Newer Snippets
Older Snippets »
11 total  XML / RSS feed