#!/bin/sh
#
# @author    Volker Theile <volker.theile@openmediavault.org>
# @author    OpenMediaVault Plugin Developers <plugins@omv-extras.org>
# @copyright Copyright (c) 2009-2013 Volker Theile
# @copyright Copyright (c) 2014-2021 OpenMediaVault Plugin Developers
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

set -e

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions

command=$1
plugin=$2
location=$3
commit=$3
tag=$(echo ${3} | tr -d '[[:space:]]')
message=$(echo ${4} | tr -d '[[:space:]]')

xpath="//services/developer"
xpathlocation="${xpath}/locations/location[uuid='${location}']"

owner=$(omv_config_get "${xpath}/owner")
sfref=$(omv_config_get "${xpath}/sharedfolderref")
sfpath=$(omv_get_sharedfolder_path "${sfref}")
temppath="/tmp/"

txpath=".tx"
txbin="/usr/bin/tx"

if [ -z "${sfpath}" ]; then
    echo "Error - shared folder not set."
    exit 1
fi

packagepath="${sfpath}/${plugin}"

initial()
{
    export LANG=C
    if [ ! -d "${packagepath}" ]; then
        echo "Cloning ${plugin} from github to ${sfpath} ..."

        cd ${sfpath}
        git clone https://github.com/OpenMediaVault-Plugin-Developers/${plugin}.git

        cd ${sfpath}/${plugin}
        oIFS=${IFS}
        IFS=$'
'
        remote_branches=$(git branch -r | grep -v HEAD | grep -v "master$")

        if [ -n "${remote_branches}" ]; then
            for rbranch in ${remote_branches}; do
                current=$(echo ${rbranch} | cut -d'/' -f2)
                git checkout -b ${current} origin/${current}
            done

            git checkout master
        fi

        IFS=${oIFS}
    fi
}

remove()
{
    if [ -d "${packagepath}" ]; then
        echo "Removing old files ..."
        rm -rfv ${packagepath}
    fi
}

build()
{
    export LANG=C
    copylocation=$(omv_config_get "${xpath}/copylocation")
    echo "Building ${plugin}..."
    rm -f ${temppath}${plugin}*.deb
    rm -rf ${temppath}${plugin}
    cp -r ${packagepath} ${temppath}
    cd ${temppath}${plugin}
    if [ -f "${temppath}${plugin}/control" ]; then
        equivs-build control 2>&1
        mv ${temppath}${plugin}/*.deb ${temppath}
    else
        # debuild -b -us -uc -I
        # debuild clean
        if grep -q "Architecture: any" debian/control; then
            for i in amd64 armhf arm64 i386; do
                echo $i
                dpkg-buildpackage -b -a $i
            done
        else
            fakeroot debian/rules clean binary 2>&1
        fi
    fi
    rm -f ${packagepath}*.deb
    cp -f ${temppath}${plugin}*.deb ${sfpath}/
    rm -f ${temppath}${plugin}*.deb
    rm -rf ${temppath}${plugin}
    chown ${owner}:users ${packagepath}*.deb
    if [ -n "${copylocation}" ]; then
        if [ -d "${copylocation}" ]; then
            echo "Copying package to ${copylocation} ..."
            cp ${packagepath}*.deb "${copylocation}"
        fi
    fi
}

update()
{
    export LANG=C
    cd ${packagepath}
    echo "Updating ${plugin} from github..."
    git pull
    git status
}

upload()
{
    remotehost=$(omv_config_get "${xpathlocation}/remotehost")
    remotepath=$(omv_config_get "${xpathlocation}/remotepath")
    port=$(omv_config_get "${xpathlocation}/port")
    username=$(omv_config_get "${xpathlocation}/username")
    password=$(omv_config_get "${xpathlocation}/password")

    search="${packagepath}_*"
    version=$(ls ${search})

    echo "Uploading ${version} to ${remotehost} ..."
    if [ -n "${password}" ]; then
        sshpass -p ${password} scp -P ${port} -o StrictHostKeyChecking=no "${version}" ${username}@${remotehost}:"${remotepath}"
    else
        su - ${owner} -c "scp -P ${port} -o StrictHostKeyChecking=no \"${version}\" ${username}@${remotehost}:\"${remotepath}\""
    fi
}

tx()
{
    repos="/root/.repos"
    tx_dir="${sfpath}/.tx"
    tx_file="${tx_dir}/config"

    mkdir -p "${tx_dir}"

    cat <<EOF > ${tx_file}
[main]
host = https://www.transifex.com
lang_map = de: de_DE, it: it_IT, ru: ru_RU, uk: uk_UK, da: da_DA, no: no_NO, sv: sv_SV, es: es_ES, fr: fr_FR, nl: nl_NL
type = PO

EOF

    # repos
    while read repo; do
        cat <<EOF >> ${tx_file}
[${repo}.${repo}pot]
file_filter = ${repo}/usr/share/openmediavault/locale/<lang>/${repo}.po
source_file = ${repo}/usr/share/openmediavault/locale/${repo}.pot
source_lang = en

EOF
    done < ${repos}

    chown -R ${owner}:users ${tx_dir}
    rm -f ${repos}
}

moveto()
{
    rm -rf ${temppath}${plugin}
    rm -rf ${temppath}${txpath}
    cp -r ${packagepath} ${temppath}
    cp -r ${sfpath}/${txpath} ${temppath}
}

movefrom()
{
    cp -rf ${temppath}${plugin} ${sfpath}/
    rm -rf ${temppath}${plugin}
}

buildpot()
{
    OMV_POT_DIR="${temppath}${plugin}/usr/share/openmediavault/locale"

    OMV_XGETTEXT_ARGS=" --keyword=_ --output-dir=${OMV_POT_DIR} \
      --output=${plugin}.pot --force-po --no-location --no-wrap \
      --sort-output --package-name=${plugin} --from-code=UTF-8 \
      --join-existing"

    moveto
    cd "${temppath}${plugin}"
    echo "Building PO template file ..." >&2
    mkdir -p "${OMV_POT_DIR}"

    # Extract strings from YAML files.
    find ./usr/share/openmediavault/workbench/ \
      \( -iname "*.yaml" \) -type f -print0 | \
      xargs -0r xgettext ${OMV_XGETTEXT_ARGS} -

    # Extract strings from PHP files in usr/share/php if it exists
    if [ -d "./usr/share/php" ]; then
      find ./usr/share/php/ \
        \( -iname "*.php" -o -iname "*.inc" \) -type f -print0 | \
        xargs -0r xgettext ${OMV_XGETTEXT_ARGS} -
    fi

    # Extract strings from PHP files in usr/share/openmediavault
    find ./usr/share/openmediavault/ \
      \( -iname "*.php" -o -iname "*.inc" \) -type f -print0 | \
      xargs -0r xgettext ${OMV_XGETTEXT_ARGS} -

    # Remove '#, c-format' comments, otherwise manuall upload of translation
    # files confuses Transifex.
    sed --in-place '/^#, c-format/d' "${OMV_POT_DIR}/${plugin}.pot"
    movefrom
}

pushpot()
{
    moveto
    ${txbin} --root="${temppath}" push --source --resource="${plugin}.${plugin}pot"
    movefrom
}

pullpo()
{
    moveto
    ${txbin} --root="${temppath}" pull --all --force --resource="${plugin}.${plugin}pot"
    movefrom
}

install()
{
    search="${packagepath}_*"
    version=$(ls ${search})

    echo "Installing ${plugin} ..."
    export LANG=C
    export DEBIAN_FRONTEND=noninteractive
    cd ${packagepath}
    dpkg -i "${version}"
    apt-get --yes --force-yes --fix-missing -f install
}

fixperms()
{
    mkconfpath="/usr/share/openmediavault/mkconf"
    localbinpath="/usr/local/bin"
    sbinpath="/usr/sbin"
    etcinitpath="/etc/init.d/"
    etcsupportpath="/etc/omv-support.d/"
    etcnetworkpath="/etc/network/if-up.d/"
    etcsudoerspath="/etc/sudoers.d/"
    sysinfopath="/usr/share/openmediavault/sysinfo/modules.d/"
    varlibcronpath="/var/lib/openmediavault/cron.d/"
    prepath="/usr/share/openmediavault/releaseupgrade/pre.d/"
    postpath="/usr/share/openmediavault/releaseupgrade/post.d/"
    sleeppath="/etc/pm/sleep.d/"
    libextraspath="/usr/lib/omvextras/"
    libsystemdsleep="/lib/systemd/system-sleep/"

    echo "Fixing permissions..."
    find "${packagepath}" -type f -exec chmod 644 {} +
    find "${packagepath}" -type d -exec chmod 755 {} +

    find "${packagepath}" -type f -name "*.sh" -exec chmod 755 {} +

    if [ -d "${packagepath}${mkconfpath}" ]; then
        chmod -R 755 "${packagepath}${mkconfpath}"/*
    fi

    if [ -d "${packagepath}${localbinpath}" ]; then
        chmod 755 "${packagepath}${localbinpath}"/*
    fi

    if [ -d "${packagepath}${sbinpath}" ]; then
        chmod 755 "${packagepath}${sbinpath}"/*
    fi

    if [ -d "${packagepath}${etcinitpath}" ]; then
        chmod 755 "${packagepath}${etcinitpath}"/*
    fi

    if [ -d "${packagepath}${etcsupportpath}" ]; then
        chmod 755 "${packagepath}${etcsupportpath}"/*
    fi

    if [ -d "${packagepath}${etcnetworkpath}" ]; then
        chmod 755 "${packagepath}${etcnetworkpath}"/*
    fi

    if [ -d "${packagepath}${etcsudoerspath}" ]; then
        chmod 0440 "${packagepath}${etcsudoerspath}"/*
        chown root:root "${packagepath}${etcsudoerspath}"/*
    fi

    if [ -d "${packagepath}${sysinfopath}" ]; then
        chmod 755 "${packagepath}${sysinfopath}"/*
    fi

    if [ -d "${packagepath}${varlibcronpath}" ]; then
        chmod 755 "${packagepath}${varlibcronpath}"/*
    fi

    if [ -f "${packagepath}/debian/rules" ]; then
        chmod 755 "${packagepath}/debian/rules"
    fi

    if [ -f "${packagepath}/debian/${plugin}.init" ]; then
        chmod 755 "${packagepath}/debian/${plugin}.init"
    fi

    if [ -f "${packagepath}/debian/${plugin}.service" ]; then
        chmod 755 "${packagepath}/debian/${plugin}.service"
    fi

    if [ -d "${packagepath}${prepath}" ]; then
        chmod 755 "${packagepath}${prepath}"/*
    fi

    if [ -d "${packagepath}${postpath}" ]; then
        chmod 755 "${packagepath}${postpath}"/*
    fi

    if [ -d "${packagepath}${sleeppath}" ]; then
        chmod 755 "${packagepath}${sleeppath}"/*
    fi

    if [ -d "${packagepath}${libextraspath}" ]; then
        chmod 755 "${packagepath}${libextraspath}"/*
    fi

    if [ -d "${packagepath}${libsystemdsleep}" ]; then
        chmod +x "${packagepath}${libsystemdsleep}"/*
    fi

    chown -R ${owner}:users "${packagepath}"
}

gitadd()
{
    cd ${packagepath}
    echo "Adding all files ..."
    git add * 2>&1
}

gitcommit()
{
    cd ${packagepath}
    git commit -m "${commit}" 2>&1
}

gittag()
{
    if [ ! -f "/root/.netrc" ]; then
        echo ".netrc not found"
        exit 1
    fi

    cd ${packagepath}
    git tag -a "${tag}" -m "${message}" 2>&1
    git push origin "${tag}" 2>&1
}

gitpush()
{
    if [ ! -f "/root/.netrc" ]; then
        echo ".netrc not found"
        exit 1
    fi

    cd ${packagepath}
    git push 2>&1
}

gitstatus()
{
    cd ${packagepath}
    git status 2>&1
}

gitdiff()
{
    cd ${packagepath}
    git diff 2>&1
}

gitBranches()
{
    cd ${packagepath}
    git branch
}

gitChangeBranch()
{
    cd ${packagepath}
    git checkout ${location} 2>&1
}

dchi()
{
    export DEBEMAIL="plugins@omv-extras.org"
    export DEBFULLNAME="OpenMediaVault Plugin Developers"
    cd ${packagepath}
    if [ -f "debian/changelog" ]; then
        echo "Increment version ..."
        dch -U --no-auto-nmu "${commit}" 2>&1
        head -n 1 debian/changelog
    else
        echo "No changelog found."
    fi
}

dcha()
{
    export DEBEMAIL="plugins@omv-extras.org"
    export DEBFULLNAME="OpenMediaVault Plugin Developers"
    cd ${packagepath}
    if [ -f "debian/changelog" ]; then
        echo "Add changelog line ..."
        dch -U --no-auto-nmu -a "${commit}" 2>&1
    else
        echo "No changelog found."
    fi
}

dchr()
{
    export DEBEMAIL="plugins@omv-extras.org"
    export DEBFULLNAME="OpenMediaVault Plugin Developers"
    cd ${packagepath}
    if [ -f "debian/changelog" ]; then
        echo "Release version ..."
        dch -U --no-auto-nmu -r "release" -u "low" 2>&1
        head -n 1 debian/changelog
    else
        echo "No changelog found."
    fi

}

omvgit()
{
    echo "Installing OMV from github ..."
    export LANG=C
    export DEBIAN_FRONTEND=noninteractive

    omvcode="openmediavault"
    omvcodepath="${sfpath}/${omvcode}"

    if [ ! -d "${omvcodepath}" ]; then
        cd ${sfpath}
        git clone https://github.com/openmediavault/openmediavault.git
    else
        cd ${omvcodepath}
        git pull
    fi

    if [ "$(omv_product_info versionname)" = "Erasmus" ]; then
        # checkout 3.x branch since 4.x has been started
        git checkout 3.x
        git pull
    fi

    # get revision
    cd ${omvcodepath}
    revision=$(git rev-parse HEAD)
    echo "Revision ${revision}..."

    # get version
    cd ${omvcodepath}/deb/openmediavault
    version=$(head -n 1 debian/changelog | cut -f2 -d"(" | cut -f1 -d")")
    echo "Version ${version}"

    # copy files to temp path to build package
    rm -rf ${temppath}openmediavault
    cp -rf ${omvcodepath}/deb/openmediavault ${temppath}
    cp -f  ${omvcodepath}/deb/openmediavault.mk ${temppath}

    # make git package
    cd ${temppath}openmediavault
    fakeroot debian/rules clean binary
    mv -v ../openmediavault_${version}_all.deb ${sfpath}/openmediavault_${version}-git${revision}_all.deb

    dpkg --force-confold -i ${sfpath}/openmediavault_${version}-git${revision}_all.deb
    apt-get --yes --force-yes --fix-missing -f install

    echo "Purging internal cache ..."
    omv_purge_internal_cache
}

changelog()
{
    export LANG=C
    cd ${packagepath}
    head debian/changelog
}

case ${command} in
    update)
        initial
        update
        fixperms
    ;;

    reset)
        remove
        initial
        update
        fixperms
    ;;

    build)
        initial
        fixperms
        build
        fixperms
    ;;

    upload)
        initial
        fixperms
        build
        fixperms
        upload
    ;;

    tx)
        tx
    ;;

    buildpot)
        initial
        buildpot
        fixperms
    ;;

    pushpot)
        initial
        pushpot
        fixperms
    ;;

    pullpo)
        initial
        pullpo
        fixperms
    ;;

    install)
        initial
        fixperms
        build
        fixperms
        install
    ;;

    add)
        fixperms
        gitadd
    ;;

    commit)
        initial
        fixperms
        gitcommit
    ;;

    push)
        initial
        fixperms
        gitpush
    ;;

    tag)
        initial
        fixperms
        gittag
    ;;

    status)
        initial
        fixperms
        gitstatus
    ;;

    diff)
        initial
        fixperms
        gitdiff
    ;;

    branches)
        initial
        fixperms > /dev/null
        gitBranches
    ;;

    changebranch)
        initial
        fixperms
        gitChangeBranch
    ;;

    dchi)
        fixperms
        dchi
    ;;

    dcha)
        initial
        fixperms
        dcha
    ;;

    dchr)
        initial
        fixperms
        dchr
    ;;

    omvgit)
        omvgit
    ;;

    changelog)
        initial
        changelog
    ;;

    *)
    ;;
esac

exit 0
