Skip to content

Instantly share code, notes, and snippets.

@allex
Last active July 4, 2018 06:00
Show Gist options
  • Save allex/75f0772f5f769e9c60b70fc54f55cedc to your computer and use it in GitHub Desktop.
Save allex/75f0772f5f769e9c60b70fc54f55cedc to your computer and use it in GitHub Desktop.
#!/bin/sh
# vim: set ft=sh fdm=manual ts=2 sw=2 sts=2 tw=85 et:
# crontab script for auto deploy
# Author: Allex Wang ([email protected])
# GistID: 75f0772f5f769e9c60b70fc54f55cedc
# GistURL: https://gist.github.com/75f0772f5f769e9c60b70fc54f55cedc
set -eE
set -o pipefail
CMD_DIR="`cd $(dirname $0); pwd`"
LOG_DIR="$CMD_DIR/logs"
LOCK_FILE="/tmp/build.lock"
SERVER_DIR="${1:-/data/www/s1.hitv.com}"
prune=${2:-0}
if [ "${SERVER_DIR:0:1}" != "/" ]; then
echo "target must be a absolute path."
exit 1
fi
mkdir -p "$SERVER_DIR" \
&& sudo chown apps.apps $SERVER_DIR -R || exit 2
echo `date`
. /etc/profile || true
[ -f "$LOCK_FILE" ] && { echo "running..."; exit 1; }
echo $$ > $LOCK_FILE
trap "[ -s "$LOCK_FILE" ] && rm -rf "$LOCK_FILE"; exit" 0 1 2 3 9 13 15
(cd $CMD_DIR/s1.hitv.com || exit 1
dest="$PWD/.deploy-cache"
tag="$SERVER_DIR"/.version
origin_head=$(git ls-remote --heads $(git config --get remote.origin.url) | grep "refs/heads/master" | cut -f 1)
if [ $origin_head != "$(git rev-parse HEAD)" ]; then
echo >&2 "HEAD and origin/master differ."
git fetch origin && git reset $origin_head --hard
fi
rev=`git log -1 --format="%h"`
if [ -f "$tag" ] && [ $(cat "$tag") = "$rev" ]; then
echo "Duplicate build, abort. (sha1: $rev)"
exit 0
fi
(rm -rf "$dest"
(mkdir -p "$dest" \
&& tar -X .gitignore -czf - ./ |(cd "$dest"; tar xzf -) \
&& echo "build done"
)
[ -d "$dest" ] || exit 1
(cd $dest; tar cz .)|([ "$prune" = "1" ] && rm -rf "$SERVER_DIR"/*; tar -C "$SERVER_DIR" --warning=none --keep-newer-files -xzvf -) \
&& echo "$rev" > "$tag"
) 2>&1 | tee $LOG_DIR/build.log
echo "done!"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment