#!/bin/bash

set -x

DOCKER_VOL="docker_volume"
SCRIPT_PATH="/var/lib/jenkins/jenkins-scripts"

mkdir ${DOCKER_VOL}
export -p > ${DOCKER_VOL}/envs
chmod +x ${DOCKER_VOL}/envs
sed --quiet 's/^\(export \)*//' ${DOCKER_VOL}/envs

#sudo docker pull ${ABS_TIZEN_STUDIO_DOCKER_IMAGE}
sudo docker run -t -d -w /share \
       -v `pwd`/`basename ${SCRIPT_PATH}`:${SCRIPT_PATH} \
       -v `pwd`/${DOCKER_VOL}:/share:rw \
       -e LANG=C.UTF-8 -e LC_ALL=C.UTF-8 \
       --name abs_${BUILD_NUMBER} ${ABS_TIZEN_STUDIO_DOCKER_IMAGE}

echo """#!/bin/bash 

source /share/envs

chown build:build -R /share 

su build -c '"python ${SCRIPT_PATH}/abs/job_abs_backend.py $1"'

""" > ${DOCKER_VOL}/build.sh
chmod +x ${DOCKER_VOL}/build.sh

cp -rf ~/.ssh ${DOCKER_VOL}/
sudo docker exec abs_${BUILD_NUMBER} bash -c "cp -r /share/.ssh /home/build/.ssh; \
       chown -R build:build /home/build/.ssh; \
       chmod 600 /home/build/.ssh/${ABS_SSH_KEY}"

sudo docker exec abs_${BUILD_NUMBER} bash -lc "./build.sh"

sudo docker stop abs_${BUILD_NUMBER}
sudo docker rm abs_${BUILD_NUMBER}

cp docker_volume/*.env .

