#!/bin/bash

cwd=`pwd`
project_name=$1
cd ${project_name}
project=`pwd`
cd $cwd
echo "Switching to project ${project_name}"
echo "          directory  ${project}"

if [ ! -d ${project} ] && [ ! -f ${project} ]; then
  echo "! Project ${project} not found"
  exit 1
fi

if [ ! -d ${project}/packaging/webui ]; then
  echo "! Project ${project} has invalid packaging layout"
  exit 1
fi

# Cleanup /var/weconfig
webroot=/var/webconfig

# Cleanup SAFe
echo "Cleaning ${webroot}"

for f in ${webroot}/SAFe ${webroot}/*_modules
do
  if [ -e $f ]; then
    echo "- Removing $f"
    if [ ! -h $f ]; then
      echo "! Real directory $f - Giving up !"
      exit 1
    fi
    if [ -h $f ]; then
      rm -f $f
    fi
  fi
done

# Cleanup http.d
httpconf=/usr/webconfig/conf/httpd.d
echo "Cleaning ${httpconf}"
for f in ${httpconf}/SAFe.conf ${httpconf}/*_modules.conf
do
  echo "- Removing $f"
  rm -f $f
done

# Installing new modules
echo "Installing web modules"

for f in ${project}/packaging/webui/SAFe_modules/*
do
  echo "- Link $f"
  ln -s $f ${webroot}/${f##*/}
done

for f in ${project}/packaging/webui/SAFe_modules/*/packaging/*.conf
do
  echo "- http config $f"
  cp $f ${httpconf}
done

# Ensure DB is accessible
chown -R webconfig /var/webconfig/SAFe/application/db

# Taking care of prod-def
echo "Updating prod-def"
if [ -f ${project}/packaging/webui/clearos_modules/app-${project_name}/src/conf/${project_name}-prod-def.xml ]; then
  cp -f ${project}/packaging/webui/clearos_modules/app-${project_name}/src/conf/${project_name}-prod-def.xml /usr/local/sng/conf
  rm -f /usr/local/sng/conf/prod-def.xml
  ln -s /usr/local/sng/conf/${project_name}-prod-def.xml /usr/local/sng/conf/prod-def.xml
fi

echo "Updating Menu"
rm -f /var/webconfig/htdocs/menus/*.en_US
python ${project}/packaging/scripts/python/sngprod.py \
  -a menu \
  -d /usr/local/sng/conf/prod-def.xml \
  -o /var/webconfig/htdocs/menus

# Update clearos template directory
if [ -d ${project}/packaging/webui/clearos_modules/app-sng-theme/webconfig/htdocs/templates/sng ]; then
  echo "Updating clearos product template"
  if [ -h /var/webconfig/htdocs/templates/sng ]; then
    rm -f /var/webconfig/htdocs/templates/sng
  fi
  if [ -d /var/webconfig/htdocs/templates/sng ]; then
    rm -rf /var/webconfig/htdocs/templates/sng
  fi

  ln -s ${project}/packaging/webui/clearos_modules/app-sng-theme/webconfig/htdocs/templates/sng /var/webconfig/htdocs/templates/sng
fi

# Restart webconfig
service webconfig restart





