#!/bin/bash
#
# ffmpeg for Ubuntu 12.04
#
# encoding: UTF-8N
#

CURRENT_DIR=$(cd $(dirname $0);pwd)
WORK_DIR=$CURRENT_DIR/ffmpeg-`date '+%Y%m%d-%H%M%S'`
mkdir $WORK_DIR
cd $WORK_DIR

# remove old packages
sudo apt-get remove ffmpeg x264 libx264-dev
sudo apt-get autoremove

# install packages
sudo apt-get update

sudo apt-get -y install build-essential checkinstall git libfaac-dev libgpac-dev \
     libjack-jackd2-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev \
     libsdl1.2-dev libtheora-dev libva-dev libvdpau-dev libvorbis-dev libvpx-dev \
     libx11-dev libxfixes-dev libxvidcore-dev texi2html yasm zlib1g-dev

# ldconfig
LD_CONF=$(grep "/usr/lib" /etc/ld.so.conf.d/libc.conf)
if [ -z "$LD_CONF" ]; then
    sudo sh -c 'echo "/usr/lib" >> /etc/ld.so.conf.d/libc.conf'
fi

LD_CONF=$(grep "/usr/local/lib" /etc/ld.so.conf.d/libc.conf)
if [ -z "$LD_CONF" ]; then
    sudo sh -c 'echo "/usr/local/lib" >> /etc/ld.so.conf.d/libc.conf'
fi

sudo ldconfig

# x264
cd $WORK_DIR
git clone git://git.videolan.org/x264
cd x264
# --disable-asm : yasm > 1.2.0
# --disable-opencl : ffmpeg libx264 not found
./configure --enable-static --disable-asm --disable-opencl
make
sudo checkinstall --pkgname=x264 --pkgversion="3:$(./version.sh | awk -F'[" ]' '/POINT/{print $4"+git"$5}')" --backup=no --deldoc=yes --fstrans=no --default
make distclean

# ffmpeg
cd $WORK_DIR
git clone --depth 1 git://source.ffmpeg.org/ffmpeg
#FFMPEG=1.2.3
#wget http://ffmpeg.org/releases/ffmpeg-${FFMPEG}.tar.gz
#tar xvfz ffmpeg-${FFMPEG}.tar.gz
cd ffmpeg
./configure --enable-gpl --enable-version3 --enable-nonfree --enable-postproc \
    --enable-libfaac --enable-libmp3lame --enable-libopencore-amrnb \
    --enable-libopencore-amrwb --enable-libtheora --enable-libvorbis \
    --enable-libvpx --enable-libx264 --enable-libxvid --enable-x11grab

make
sudo checkinstall --pkgname=ffmpeg --pkgversion="5:$(./version.sh | awk -F'[-]' '{print $2$3$4"+git"$5}')" --backup=no --deldoc=yes --fstrans=no --default
hash x264 ffmpeg ffplay ffprobe
make distclean

sudo ldconfig

# -----------------------------------------------------------------------------
# remove work directory
cd $CURRENT_DIR
echo -n "remove work directory ? [y]es, or [n]o: "
read DEL_WORK_DIR
if [ ${DEL_WORK_DIR} = "y" ]; then
    rm -rf ${WORK_DIR}
fi
