on topic/v0.2 help sign in
grenade/mafia
123 lines 2.8 kB history raw
1#!/bin/sh -eu
3: ${MAFIA_HOME:=$HOME/.mafia}
5fetch_latest () {
6 if [ -z ${MAFIA_TEST_MODE+x} ]; then
7 TZ=$(date +"%T")
8 curl --silent "https://raw.githubusercontent.com/ambiata/mafia/master/script/mafia?$TZ"
9 else
10 cat ../script/mafia
11 fi
14latest_version () {
15 git ls-remote https://github.com/ambiata/mafia | grep refs/heads/master | cut -f 1
18local_version () {
19 awk '/^# Version: / { print $3; exit 0; }' $0
22run_upgrade () {
23 MAFIA_TEMP=$(mktemp 2>/dev/null || mktemp -t 'upgrade_mafia')
25 clean_up () {
26 rm -f "$MAFIA_TEMP"
27 }
29 trap clean_up EXIT
31 MAFIA_CUR="$0"
33 if [ -L "$MAFIA_CUR" ]; then
34 echo 'Refusing to overwrite a symlink; run `upgrade` from the canonical path.' >&2
35 exit 1
36 fi
38 echo "Checking for a new version of mafia ..."
39 fetch_latest > $MAFIA_TEMP
41 LATEST_VERSION=$(latest_version)
42 echo "# Version: $LATEST_VERSION" >> $MAFIA_TEMP
44 if ! cmp $MAFIA_CUR $MAFIA_TEMP >/dev/null 2>&1; then
45 mv $MAFIA_TEMP $MAFIA_CUR
46 chmod +x $MAFIA_CUR
47 echo "New version found and upgraded. You can now commit it to your git repo."
48 else
49 echo "You have latest mafia."
50 fi
53exec_mafia () {
54 MAFIA_VERSION=$(local_version)
56 if [ "x$MAFIA_VERSION" = "x" ]; then
57 # If we can't find the mafia version, then we need to upgrade the script.
58 run_upgrade
59 else
60 MAFIA_BIN=$MAFIA_HOME/bin
61 MAFIA_FILE=mafia-$MAFIA_VERSION
62 MAFIA_PATH=$MAFIA_BIN/$MAFIA_FILE
64 [ -f "$MAFIA_PATH" ] || {
65 # Create a temporary directory which will be deleted when the script
66 # terminates. Unfortunately `mktemp` doesn't behave the same on
67 # Linux and OS/X so we need to try two different approaches.
68 MAFIA_TEMP=$(mktemp -d 2>/dev/null || mktemp -d -t 'exec_mafia')
70 # Create a temporary file in MAFIA_BIN so we can do an atomic copy/move dance.
71 mkdir -p $MAFIA_BIN
73 clean_up () {
74 rm -rf "$MAFIA_TEMP"
75 }
77 trap clean_up EXIT
79 echo "Building $MAFIA_FILE in $MAFIA_TEMP"
81 ( cd "$MAFIA_TEMP"
83 git clone https://github.com/ambiata/mafia
84 cd mafia
86 git reset --hard $MAFIA_VERSION
88 bin/bootstrap ) || exit $?
90 MAFIA_PATH_TEMP=$(mktemp --tmpdir=$MAFIA_BIN $MAFIA_FILE-XXXXXX 2>/dev/null || TMPDIR=$MAFIA_BIN mktemp -t $MAFIA_FILE)
92 clean_up_temp () {
93 clean_up
94 rm -f "$MAFIA_PATH_TEMP"
95 }
96 trap clean_up_temp EXIT
98 cp "$MAFIA_TEMP/mafia/.cabal-sandbox/bin/mafia" "$MAFIA_PATH_TEMP"
99 chmod 755 "$MAFIA_PATH_TEMP"
100 mv "$MAFIA_PATH_TEMP" "$MAFIA_PATH"
102 clean_up_temp
103 }
105 exec $MAFIA_PATH "$@"
106 fi
110# The actual start of the script.....
113if [ $# -gt 0 ]; then
114 MODE="$1"
115else
116 MODE=""
117fi
119case "$MODE" in
120upgrade) shift; run_upgrade "$@" ;;
121*) exec_mafia "$@"
122esac
123# Version: 360716306a06db842ec022a7b9f161d2208483f0