#!/bin/bash -e

set -o pipefail
set -x

DB_NAME=zencart
DB_USER=zencart
DB_PREFIX=zen_

ADMIN_NAME=admin
ADMIN_PASS=turnkey
ADMIN_MAIL=admin@example.com

SRC=/usr/local/src
WEBROOT=/var/www/zencart
VERSION=v2.2.2
TAG_COMMIT=63cf0ec3324d49767d25a07d168cdecb829e4d2a
ARCHIVE_SHA256=5fdb86e97460975b5f7a5e25affd3616b2470b96001aa3f1192bd0cc4c0efadc

unzip -q "$SRC/zencart-$VERSION.zip" -d "$(dirname "$WEBROOT")"
mv "$(dirname "$WEBROOT")/zencart-${VERSION#v}" "$WEBROOT"
rm -f "$SRC/zencart-$VERSION.zip"

install -d -m 0755 /usr/local/share/turnkey-zencart
python3 /usr/local/lib/turnkey-zencart/content-update-plan record "$WEBROOT" \
    /usr/local/share/turnkey-zencart/content-baseline.json

# Give the wizard useful defaults for the enabled check payment method while
# allowing stores without a postal address to configure other payment methods.
python3 /usr/local/lib/turnkey-zencart/customize-wizard "$WEBROOT/admin/index_setup_wizard.php"

# Use the configured store name in page titles and remove sample header copy.
mkdir -p "$WEBROOT/includes/languages/english/extra_definitions"
cat > "$WEBROOT/includes/languages/english/extra_definitions/lang.turnkey.php" <<'PHP'
<?php
return ['TITLE' => STORE_NAME, 'SITE_TAGLINE' => '', 'HEADER_SALES_TEXT' => ''];
PHP

# Give customers a useful default while retaining the editable content page.
for page in "$WEBROOT"/includes/languages/english/html_includes/{,classic/,responsive_classic/}define_checkout_success.php; do
    printf '%s\n' '<p>Review your order details below.</p>' > "$page"
done
for theme in template_default classic responsive_classic; do
    css="$WEBROOT/includes/templates/$theme/css/stylesheet_turnkey_checkout.css"
    printf '%s\n' '#checkoutSuccessContactLink { clear: both; }' > "$css"
    printf '%s\n' '#checkoutsuccessBody #searchContent input[name="keyword"] { max-width: 100%; box-sizing: border-box; }' >> "$css"
    printf '%s\n' '#checkoutsuccessBody .sideBoxContent { overflow-wrap: anywhere; }' >> "$css"
    printf '%s\n' '@media (min-width: 601px) and (max-width: 850px) { #checkoutsuccessBody .leftBoxHeading { font-size: 0.9em; } }' >> "$css"
done

grep -qx "define('PROJECT_VERSION_MAJOR', '2');" "$WEBROOT/includes/version.php"
grep -qx "define('PROJECT_VERSION_MINOR', '2.2');" "$WEBROOT/includes/version.php"

install -d -m 0755 /usr/local/share/turnkey-zencart
cat > /usr/local/share/turnkey-zencart/source <<EOF
version=$VERSION
tag_commit=$TAG_COMMIT
archive_sha256=$ARCHIVE_SHA256
channel=official Zen Cart v2.2 patch releases
EOF

mv "$WEBROOT/includes/dist-configure.php" "$WEBROOT/includes/configure.php"
mv "$WEBROOT/admin/includes/dist-configure.php" "$WEBROOT/admin/includes/configure.php"
printf '\ndefine(\x27DEVELOPER_MODE\x27, true);\n' >> "$WEBROOT/zc_install/includes/localConfig.php"

for path in \
    pub media cache images download logs admin/backups admin/images/graphs \
    includes/languages/english/html_includes; do
    chown -R www-data:www-data "$WEBROOT/$path"
done
chown www-data:www-data \
    "$WEBROOT/includes/configure.php" \
    "$WEBROOT/admin/includes/configure.php"
chown www-data:www-data "$WEBROOT/zc_install/includes/nginx_conf"

for php_ini in /etc/php/*/apache2/php.ini; do
    sed -i 's|^;date.timezone.*|date.timezone = "UTC"|' "$php_ini"
done

a2dissite 000-default
a2ensite zencart
a2enmod rewrite

service mysql start
service apache2 start
mysqladmin create "$DB_NAME"

set +x
DB_PASS=$(mcookie)
mysql --batch --execute "CREATE USER '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS'; GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost'; FLUSH PRIVILEGES;"

cookie=$(mktemp /run/zencart-install-cookie.XXXXXX)
trap 'rm -f "$cookie"' EXIT
install_url=http://127.0.0.1/zc_install
curl_session=(curl -fsS -c "$cookie" -b "$cookie")
system_args=(
    --data-urlencode lng=en_us
    --data-urlencode adminDir=admin
    --data-urlencode agreeLicense=on
    --data-urlencode http_server_catalog=http://127.0.0.1
    --data-urlencode https_server_catalog=https://127.0.0.1
    --data-urlencode enable_ssl_catalog=true
    --data-urlencode dir_ws_http_catalog=/
    --data-urlencode dir_ws_https_catalog=/
    --data-urlencode http_url_catalog=http://127.0.0.1/
    --data-urlencode https_url_catalog=https://127.0.0.1/
    --data-urlencode detected_http_server_catalog=http://127.0.0.1
    --data-urlencode detected_https_server_catalog=https://127.0.0.1
    --data-urlencode "physical_path=$WEBROOT/"
    --data-urlencode http_server_admin=https://127.0.0.1
    --data-urlencode installer_method=TurnKey-Linux-appliance
)
database_args=(
    --data-urlencode db_type=mysql
    --data-urlencode db_host=localhost
    --data-urlencode "db_user=$DB_USER"
    --data-urlencode "db_password=$DB_PASS"
    --data-urlencode "db_name=$DB_NAME"
    --data-urlencode db_charset=utf8mb4
    --data-urlencode "db_prefix=$DB_PREFIX"
    --data-urlencode sql_cache_method=none
)

printf 'zencart_install_stage=database-page\n' >&2
"${curl_session[@]}" "${system_args[@]}" "$install_url/index.php?main_page=database" >/dev/null

printf 'zencart_install_stage=database-check\n' >&2
db_test=$("${curl_session[@]}" "${database_args[@]}" "$install_url/ajaxTestDBConnection.php")
printf '%s' "$db_test" | jq -e '.error == false' >/dev/null

printf 'zencart_install_stage=schema-load\n' >&2
db_load=$("${curl_session[@]}" "${database_args[@]}" "$install_url/ajaxLoadMainSql.php")
printf '%s' "$db_load" | jq -e '.error == false' >/dev/null

printf 'zencart_install_stage=admin-ajax\n' >&2
admin_setup=$("${curl_session[@]}" \
    --data-urlencode admin_user=$ADMIN_NAME \
    --data-urlencode admin_email=$ADMIN_MAIL \
    --data-urlencode admin_email2=$ADMIN_MAIL \
    --data-urlencode adminDir=admin \
    "$install_url/ajaxAdminSetup.php")
printf '%s' "$admin_setup" | jq -e '
    .error != true and
    .adminDir == "admin" and
    .adminNewDir == "admin" and
    .changedDir == 0
' >/dev/null

printf 'zencart_install_stage=admin-page\n' >&2
"${curl_session[@]}" \
    "${system_args[@]}" "${database_args[@]}" \
    --data-urlencode changedDir=0 \
    --data-urlencode adminNewDir=admin \
    "$install_url/index.php?main_page=admin_setup" >/dev/null

printf 'zencart_install_stage=completion-page\n' >&2
if ! "${curl_session[@]}" \
        --insecure \
        "${system_args[@]}" "${database_args[@]}" \
        --data-urlencode admin_user=$ADMIN_NAME \
        --data-urlencode admin_email=$ADMIN_MAIL \
        --data-urlencode admin_email2=$ADMIN_MAIL \
        --data-urlencode admin_password=$ADMIN_PASS \
        --data-urlencode admin_directory=admin \
        "https://127.0.0.1/zc_install/index.php?main_page=completion" >/dev/null; then
    printf 'zencart_install_stage=completion-page-error-log\n' >&2
    tail -n 80 /var/log/apache2/error.log >&2 || true
    for log in "$WEBROOT"/logs/zcInstallDEBUG-*.log; do
        [ -f "$log" ] || continue
        printf 'zencart_install_php_log=%s\n' "$(basename "$log")" >&2
        tail -n 80 "$log" >&2 || true
    done
    exit 22
fi

printf 'zencart_install_stage=admin-finalization\n' >&2
ADMIN_HASH=$(php -r 'echo password_hash($argv[1], PASSWORD_DEFAULT);' "$ADMIN_PASS")
DATE=$(date '+%Y-%m-%d %H:%M:%S')
mysql --batch --execute "UPDATE $DB_NAME.${DB_PREFIX}admin SET admin_pass='$ADMIN_HASH', pwd_last_change_date='$DATE', last_login_date='$DATE', reset_token='' WHERE admin_name='$ADMIN_NAME';"
unset ADMIN_HASH DB_PASS
rm -f "$cookie"
trap - EXIT
set -x

rm -rf "$WEBROOT/zc_install"
mv "$WEBROOT/admin" "$WEBROOT/manage"

chown -R root:root "$WEBROOT"
for path in \
    pub media cache images download logs manage/backups manage/images/graphs \
    includes/languages/english/html_includes; do
    chown -R www-data:www-data "$WEBROOT/$path"
done
chown root:www-data \
    "$WEBROOT/includes/configure.php" \
    "$WEBROOT/manage/includes/configure.php"
chmod 0640 \
    "$WEBROOT/includes/configure.php" \
    "$WEBROOT/manage/includes/configure.php"

# Refuse an automatic upstream update if it would overwrite merchant edits to
# these managed files. Editable content and appliance overrides are separate.
(cd "$WEBROOT" && sha256sum \
    manage/index_setup_wizard.php \
    includes/languages/english/lang.header.php \
    includes/languages/english/lang.meta_tags.php \
    includes/templates/{template_default,classic,responsive_classic}/css/stylesheet.css \
    > /usr/local/share/turnkey-zencart/managed.sha256)

service mysql stop
service apache2 stop
