#!/usr/bin/env bash

# Site publish script (with scp or git)

# jssg-pub options
# ======================

# 1) jssg-pub scp

# For this, add the following to a file named ".env" :

# WWW_PUB_USER="<remote user>"
# WWW_PUB_HOST="<remote dns hostname or ip>"
# WWW_PUB_PATH="<remote directory path>"
# WWW_PUB_IDENTITY="<path to local SSH private key>"

# 2) jssg-pub git

# For this, add the following to a file named ".env" :

# WWW_PUB_REPO_DIR="<path to local repo>"
# WWW_PUB_REPO_BRANCH="<repo branch>"


pub_opt=$1

if [ -z $pub_opt ]; then
    echo "error: publish option not set"
    echo "Options:"
    echo -e "\tjssg-pub scp"
    echo -e "\tjssg-pub git"
    exit 1
fi

vars_scp=(
    WWW_PUB_USER
    WWW_PUB_HOST
    WWW_PUB_PATH
    WWW_PUB_IDENTITY
)

vars_git=(
    WWW_PUB_REPO_DIR
    WWW_PUB_REPO_BRANCH
)

check_vars() {

    for var in "$@"
    do
        eval "env_var=$`echo $var`"
        if [ -z "$env_var" ]; then
            echo "error: env var $var not set"
            exit 1
        fi
    done
}


pub_scp() {

    check_vars ${vars_scp[@]}

    echo "Publishing www to $WWW_PUB_HOST:$WWW_PUB_PATH with scp (`ssh -V 2>&1`)"
    echo "User: $WWW_PUB_USER"
    echo -e "Identity: $WWW_PUB_IDENTITY\n"
    scp -r -i $WWW_PUB_IDENTITY www/* $WWW_PUB_USER@$WWW_PUB_HOST:$WWW_PUB_PATH

}

pub_git() {

    check_vars ${vars_git[@]}

    eval repo_dir=$WWW_PUB_REPO_DIR

    if [ ! -d $repo_dir ]; then
        echo "error: git repo dir not found: $WWW_PUB_REPO_DIR"
        exit 1
    fi

    if [ ! -d "$repo_dir/.git" ]; then
        echo "error: not a git repo: $WWW_PUB_REPO_DIR"
        exit 1
    fi

    source_dir=`pwd`

    echo "Publishing www with git"
    echo "Repo: $WWW_PUB_REPO_DIR"
    echo -e "Branch: $WWW_PUB_REPO_BRANCH\n"

    cd $repo_dir
    if [[ ! `pwd` =~ $repo_dir ]]; then exit 1; fi

    checkout=`git checkout $WWW_PUB_REPO_BRANCH 2>&1`
    if [[ ! $checkout =~ "Already on" ]]; then echo $checkout; fi

    cp -r "$source_dir/www/"* $repo_dir
    git add .

    status=`git status 2>&1`
    if [[ ! $status =~ "nothing to commit" ]]; then
        git status
        git commit -m "Site Update: `date "+%Y-%m-%dT%H:%M:%S"`"
        git push origin $WWW_PUB_REPO_BRANCH
    else
        echo "No changes to commit/publish."
    fi
}


if [ ! -d www ]; then
    echo "error: www directory not found"
    exit 1
fi

if [ -f .env ]; then
    source .env
    if [ $pub_opt == "scp" ]; then
        pub_scp
    elif [ $pub_opt == "git" ]; then
        pub_git
    else
        echo "error: invalid publish option: $pub_opt, valid options are: scp git"
        exit 1
    fi
else
    echo "error: .env file not found"
    exit 1
fi


