#!/bin/sh

wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat/jenkins.repo
rpm --import http://pkg.jenkins-ci.org/redhat/jenkins-ci.org.key
yum install -y jenkins 
yum install -y java-1.7.0-openjdk-devel

#CHK=`grep "dport 8080" /etc/sysconfig/iptables`
#if [ "$CHK" = '' ]
#then
#  RULENUM=`iptables-save |grep INPUT |grep -n "dport 22"|awk -F : '{print $1}'`
#  iptables -I  INPUT ${RULENUM} -p tcp -m state --state NEW -m tcp --dport 8080 -j ACCEPT
#  iptables-save > /etc/sysconfig/iptables
#fi

if [ ! -d /var/lib/jenkins/persona ]
then
  git clone https://github.com/okamototk/jenkins-persona-hudmi /var/lib/jenkins/persona
fi

if [ ! -f /etc/httpd/conf.d/jenkins.conf ]
then
  cp inst-script/rhel6/httpd-jenkins.conf /etc/httpd/conf.d/jenkins.conf
fi
 
sed -i 's/JENKINS_ARGS=""/JENKINS_ARGS="--prefix=\/jenkins"/' /etc/sysconfig/jenkins

if [ ! -f /var/lib/jenkins/config.xml ]
then
  cp config/jenkins-config.xml /var/lib/jenkins/config.xml
fi

if [ ! -f /var/lib/jenkins/plugins ]
then
  mkdir /var/lib/jenkins/plugins
  chown jenkins.jenkins /var/lib/jenkins/plugins
fi

service jenkins start

RET=-1
until  [ "$RET" -eq "0" ]
do
  sleep 3
  wget  -O $INSTALL_DIR/bin/jenkins-cli.jar http://localhost:8080/jenkins/jnlpJars/jenkins-cli.jar
  RET=$?
done

wget -O /tmp/default.js http://updates.jenkins-ci.org/update-center.json
 
# remove first and last line javascript wrapper
sed '1d;$d' /tmp/default.js > /tmp/default.json
  
# Now push it to the update URL
curl -X POST -H "Accept: application/json" -d @/tmp/default.json http://localhost:8080/jenkins/updateCenter/byId/default/postBack --verbose

RET=-1
until  [ "$RET" -eq "0" ]
do
  sleep 3
  java -jar $INSTALL_DIR/bin/jenkins-cli.jar -s http://localhost:8080/jenkins/ install-plugin reverse-proxy-auth-plugin
  RET=$?
done

java -jar $INSTALL_DIR/bin/jenkins-cli.jar -s http://localhost:8080/jenkins/ install-plugin reverse-proxy-auth-plugin
java -jar $INSTALL_DIR/bin/jenkins-cli.jar -s http://localhost:8080/jenkins/ install-plugin persona
java -jar $INSTALL_DIR/bin/jenkins-cli.jar -s http://localhost:8080/jenkins/ install-plugin git
java -jar $INSTALL_DIR/bin/jenkins-cli.jar -s http://localhost:8080/jenkins/ install-plugin redmine
java -jar $INSTALL_DIR/bin/jenkins-cli.jar -s http://localhost:8080/jenkins/ install-plugin dashboard-view

sleep 10

java -jar $INSTALL_DIR/bin/jenkins-cli.jar -s http://localhost:8080/jenkins/ restart

